Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 372
riccardo.cardin Avatar asked Sep 05 '17 10:09

riccardo.cardin


1 Answers

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

like image 161
Konrad 'ktoso' Malawski Avatar answered Oct 14 '22 20:10

Konrad 'ktoso' Malawski