How do I convert a classic ActorContext to a typed one

171 views Asked by At

Say I define some messages:

sealed trait Command
case class A(i: Int) extends Command
case class B(str: String) extends Command

And then a classic actor as below to handle these messages. On creation I need access to the ActorContext but as a typed context not a classic

class MyActor extends Actor {

  val typedContext: ActorContext[Command] = ???

  def receive = {
    case A(i) =>
      // Do something with i
    case B(str)
     // Do something with str

  }
}

I know I can do self.toTyped[Command] to get the typed self reference. But I cannot find anything similar for the ActorContext. How would I go about converting?

1

There are 1 answers

0
Levi Ramsey On BEST ANSWER

There is no conversion from a classic ActorContext to a typed ActorContext. About the only things a typed ActorContext can do that a classic ActorContext can't are:

  • ask another actor and adapt the result (to do that in classic, you use the classic ask pattern: import akka.pattern.ask)
  • pipe a future to the actor (for that import akka.pattern.pipe)
  • take advantage of a typed actor's lifecycle (spawn, watch, unwatch, stop)

For the last one, you can

import akka.actor.typed.scaladsl.adapter.ClassicActorContextOps

which will add

  • spawn/spawnAnonymous
  • watch
  • unwatch
  • stop

methods which handle typed.