8

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?

jdevelop
  • 12,176
  • 10
  • 56
  • 112
  • 1
    I have opened a ticket to improve the docs, in the meantime study the API: http://doc.akka.io/api/akka/2.0.1/#akka.event.EventStream – Viktor Klang May 28 '12 at 13:13
  • Actually I very much like to see an example of that too. Currently we're using Guava's EventBus for simple GUI event handling. For heavy duty work however I'd like to introduce Akka and get rid of Guava altogether. It's a bit daft to keep two event handling libraries in the same application... – Jan Goyvaerts Jun 11 '12 at 11:53

2 Answers2

11

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);
  }
}
Jan Goyvaerts
  • 2,913
  • 4
  • 35
  • 48
0

I don't know for sure if the code from @Jan Goyvaerts is still up to date, as of September 2019 this line is not working:

final ActorRef actor = actorSystem.actorOf(new Props(SeverEventHandler.class));

I think the correct way to do this now might be:

ActorRef newActor = system.actorOf(Props.create(AATestAkkaEventBus.class));

I am by no means sure of this, please correct me if I'm wrong

  • It appears that at least in the Play Framework 2.6 or later, one way is to have a static getProps() defined as in `public static Props getProps() {return Props.create(HelloActor.class);}` defined in your actor then you would call that getProps as in `helloActor = system.actorOf(HelloActor.getProps());` – Manabu Tokunaga Feb 07 '21 at 03:59