Search code examples
akkaobserver-pattern

Howto create a observer like communication between actors with Akka


In classical programming, I use the obeserver pattern in case I want to notify observers about changes.

What is the equivalent pattern in Akka?

Use case:

  • An actor (PropertyServiceActor) is reading and caching properties form the DB
  • Different actors can register to the PropertyServiceActor
  • If a property changes, the PropertyServiceActor notifies the registered actors about the change

Solution

  • Take a look at BroadcastGroup

    //Create group
    val paths = List("/user/workers/w1", "/user/workers/w2", "/user/workers/w3")
    val observers: ActorRef =  context.actorOf(BroadcastGroup(paths).props(), "observers")
    

    To notify all observers just send message to observers ActorRef. Also you can add and remove observers by sending akka.routing.AddRoutee and akka.routing.RemoveRoutee.

    You can find more routing docs.