Akka: using akka-typed to implement the active object pattern

Akka's Typed Actors' documentation states that it will be superseded by Akka Introduced . I am guessing that Akka Typed can be used to create an Active Object template ; but it is not very clear to me. Here's my attempt so far; I know it stinks: D

object HelloWorld {
  final case class Greet(whom: String, replyTo: ActorRef[Greeted])
  final case class Greeted(whom: String)

  private val greeter = Static[Greet] { msg ⇒
    println(s"Hello ${msg.whom}!")
    msg.replyTo ! Greeted(msg.whom)
  }

  private val system = ActorSystem("HelloWorld", Props(greeter))

  def greet(whom: String): Future[Greeted] = system ? (Greet(whom, _))
}

      

Greetings

+3


source to share


1 answer


The active object pattern defined by the referenced page is undesirable for all the reasons why TypedActors are being removed: the fact that a method is executing asynchronously is so important that it should not be obscured by technologies such as proxy objects that implement normal interfaces. Instead, Akka Typed allows you to write almost the same code as if it were an active object, keeping an asynchronous marker: instead of choosing a method with a syntax, .

you send a message using ?

(or !

if the protocol is not a simple request-response). Your example would look like:

object HelloWorld {
  final case class Greet(whom: String)(replyTo: ActorRef[Greeted])
  final case class Greeted(whom: String)

  val greeter = Static[Greet] { msg ⇒
    println(s"Hello ${msg.whom}!")
    msg.replyTo ! Greeted(msg.whom)
  }
}

object Sample extends App {
  import HelloWorld._
  val system = ActorSystem("HelloWorld", Props(greeter))
  val fg = system ? Greet("John")
}

      



Note that creating a separate thread (or ActorSystem) for each object may sound good according to the classic pattern, but doing so predetermines many of the benefits of a message-driven architecture, namely that many Actors can use the same resources to be more efficient. execution, and they can create hierarchies of control for principled failover, etc.

+2


source







All Articles