Search code examples
akkaakka-typed

Does akka-typed create actors when I use behavior combinator like And?


In my system I want an actor A to send the same messages to actors B,C,D. Instead of creating the three actors, I was thinking of just combining their behaviors with an And behavior contaminator, and then passing that behavior to A.

If I do this, how many actors will get created? Will I get just one actor with three behaviors in it, or three actors with separate behaviors?

Here is my real code using the non-And approach, for concreteness (see how ReplyGenerator gets passed the references to other actors):

object Foobar {
  def foobar(): Behavior[Request] =
  ContextAware[Request] {
    context =>
      val foo1 = context.spawn(Props(Foo1.behavior()), "foo1")
      val foo2 = context.spawn(Props(Foo2.behavior()), "foo2")
      val foo3 = context.spawn(Props(Foo3.behavior()), "foo3")
      val generator = context.spawn(Props(ReplyGenerator.behavior(List(foo1, foo2, foo3))),
        "generator")

      Static {
        case request: Request =>
          generator ! request
      }
  }
}

and here is the ReplyGenerator behavior that sends the same message to all subscribers:

object ReplyGenerator {
def behavior(subscribers: List[ActorRef[Reply]]): Behavior[Request] = {
    Static {
      case request: Request =>
        subscribers.foreach(_ ! Reply.empty)
    }
 }

Considering that I want the actors foo 1,2,3 to run in parallel, can And combinator be used here instead?

Thank you.


Solution

  • If you mean execution parallelism then you’ll have to create separate Actors (by separate spawn calls) as you do in the example code—using And will only create a single Actor that runs the contained behaviors one after the other.