Search code examples
scalaakkareactive-programmingcomposition

Compose more than one receive function in Akka Actors


I have an Akka Actor that manages some messages, like Find, Query, that forward a new message to others types of actors. These actors will respond with new types of messages.

class Actorbase extends Actor {
  override def receive = {
     /* The two message below are related to each other */
     case Find(coll, id) => // Do something
     case QueryAck(key, value, u) => // Do something
     /* The three message below are related to each other */
     case Upsert(collection, id, value) => // Do something
     case Response.UpsertNAck(key, msg, u) => // Do something
     case Response.UpsertAck(key, u) => // Do something
     /* And so on... */
  }
}

In the above example, QueryAck is the response message of the forward of a message of type Find. UpsertNAck and UpsertAck are possible responses to an Upsert message.

To make the code more readable and maintainable, I wish to group the two sets of cases in two dedicated methods, i.e. manageQueries and manageUpserts, obtaining something similar to the following code.

class Actorbase extends Actor {
  override def receive = {
     manageQueries.andThen(manageUpserts)
  }
}

Is is possible? May I need to declare more than one method returning a Receive object and then compose them in some way?

Thanks a lot.


Solution

  • The Receive is just a type alias for PartialFunction[Any, Unit], so you can just define such anywhere and combine them using f1 orElse f2:

    val manageQueries: Receive = { case ... }
    val manageUpserts: Receive = { case ... }
    
    def receive = manageQueries.orElse(manageUpserts) 
    

    Hope this helps