Home > OS >  Scala Akka how to create a Typed ActorContext in route
Scala Akka how to create a Typed ActorContext in route

Time:09-09

I am pretty new in Scala Akka . Say I am spawning a Configuration child actor,

object Configuration {
 
  def apply(): Behavior[ConfigurationMessage] = Behaviors.setup(context => new Configuration(context))
 
} 

Now I need same context ActorContext[ConfigurationMessage] in my HTTP router to do some operation.

How can I create the same ActorContext there

CodePudding user response:

The ActorContext cannot be used outside of the actor it's associated with, including in an HTTP router. Any ActorContext which leaks out of an actor (e.g. by sending it as a message) will, by design, throw an exception and not do anything for most operations if it's used outside of its actor.

The only operations on the ActorContext which could possibly be used outside of the associated actor are:

  • context.ask and friends can be just as easily replaced with a Future-returning ask on the target RecipientRef with the message send occurring in a foreach callback on the future.
  • context.executionContext: can just as easily use system.executionContext (which will typically be the same) or by looking up via dispatchers
  • context.pipeToSelf is probably best done as a send in a foreach callback on the future
  • context.scheduleOnce is better done using the system scheduler directly
  • context.self is kind of pointless, as you'd have to have the ActorRef already in order to leak the ActorContext
  • context.system is likewise pointless, as you already have the system
  • Related