Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of Akka EventBus for Java

Need some advice of how to use EventBus provided by Akka in Java (not Scala!). The documentation on website seems to be incomplete: http://doc.akka.io/docs/akka/2.0.1/java/event-bus.html

As far as I understood, actor should be created to react on specific messages, like:

final ActorSystem actorSystem = ActorSystem.create("ServerEvents");
final ActorRef actor = actorSystem.actorOf(new Props(SeverEventHandler.class));
actorSystem.eventStream().subscribe(actor,ServerMessage.class);

But now it's not clear how to send a message to the event bus.

Can somebody please share some good tutorials/examples/etc?

like image 205
jdevelop Avatar asked May 28 '12 08:05

jdevelop


People also ask

What is EventBus in Java?

EventBus is a publish/subscribe event bus for Android and Java. EventBus... simplifies the communication between components. decouples event senders and receivers. performs well with Activities, Fragments, and background threads.

What is Akka framework in Java?

Akka is a toolkit for building highly concurrent, distributed, and resilient message-driven applications for Java and Scala. Akka Insights is intelligent monitoring and observability purpose built for Akka.

What is EventBus pattern?

Event Bus Pattern There are many patterns devoted to reducing component coupling. An event bus is one such pattern where objects can "subscribe" to receive certain specific "events" from the bus. As an event is "published" to the event bus, it will be propagated to any subscriber which is interested in the event type.

What is EventBus used for?

EventBus is an open-source library for Android and Java using the publisher/subscriber pattern for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code – simplifying the code, removing dependencies, and speeding up app development.


1 Answers

I think you're just one line short:

final ActorSystem actorSystem = ActorSystem.create("ServerEvents");
final ActorRef actor = actorSystem.actorOf(new Props(SeverEventHandler.class));
actorSystem.eventStream().subscribe(actor,ServerMessage.class);

actorSystem.eventStream().publish(new ServerMessage()); <<== add this

While ServerEventHandler should be something like

public class ServerEventHandler extends UntypedActor {
  @Override
  public void onReceive(final Object message) {
    System.out.println("Got event in thread: " + Thread.currentThread().getName());
    System.out.println("Event: " + message);
  }
}
like image 123
Jan Goyvaerts Avatar answered Oct 13 '22 02:10

Jan Goyvaerts