5

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.

riccardo.cardin
  • 7,971
  • 5
  • 57
  • 106

1 Answers1

10

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

Konrad 'ktoso' Malawski
  • 13,102
  • 3
  • 47
  • 52
  • Thanks for the response. Do you think it is better the approach I described in the question or the one exposed in [this](https://stackoverflow.com/questions/8681444/composing-trait-behavior-in-scala-in-an-akka-receive-method?rq=1) SO answer? – riccardo.cardin Sep 05 '17 at 10:26
  • 2
    This is better than the other one I think (as a maintainer of the project) – Konrad 'ktoso' Malawski Sep 05 '17 at 11:49