akka typed actors, how to expose / share child actor's actoref

71 Views Asked by At

Using akka-actor-typed 2.8.x, how does one gain access to spawned child actor's actorRef?

I have a guardian actor that spawns a child actor and registers it with receptionist. Then in my route traits I use the receptionist.find to locate the actor and use it which then gives me a future[actorref]. I'd prefer to either pass the child actorRef as a parameter or expose in trait mixin but am unsure how to do this.

ActorSytem is created with guardian actor which then in turn spawns the child actor (RedisActor).

guardian and ActorSystem

  val guardian: Behavior[NotUsed] = Behaviors.setup { context =>
    val redisActor = context.spawn(RedisActor(redisUrl), "redis-actor")
    context.system.receptionist ! Receptionist.Register(RedisActor.RedisActorServiceKey, redisActor)
    Behaviors.empty
  }

  implicit val system: ActorSystem[NotUsed] = ActorSystem[NotUsed](guardian, "AdminHttpServer")

and lastly, RedisActor:

object RedisActor {
  def apply1(redisUrl: String): Behavior[RedisCommands] =
    Behaviors.setup(context => new RedisActor(context, redisUrl))

  def apply(redisUrl: String): Behavior[RedisCommands] =
    Behaviors.supervise(Behaviors.setup[RedisCommands](context => new RedisActor(context, redisUrl)))
      .onFailure(SupervisorStrategy.restart) //TODO look at wait time
   ...
}
class RedisActor(context: ActorContext[RedisCommands], redisUrl: String) extends AbstractBehavior[RedisActor.RedisCommands](context) {
   ...
}

Challenge, here is that redisActor is 'hidden' within guardian function and I would like to get access to it without having to use receptionist. Is there a different way to spawn the child, something like:

val redisActor = system....spawn(RedisActor(redisUrl), "redis-actor")

There must be as docs hint at multiple ways but I am not seeing it.

1

There are 1 best solutions below

6
David Ogren On

The most straightforward approach would be to define a message type that the guardian could reply to with an ActorRef to its child.

The docs for creating actors have a direct example of this: https://doc.akka.io/docs/akka/current/typed/actor-lifecycle.html#spawning-children where the parent creates a child and returns it in response to a SayHello message. The only difference between your scenario and the scenario of the example is that you are creating the child in the guardian's setup and the example spawns a child per message received.