Trying Akka Typed to make typed response

Passed 4 years since MEAP was stared, Akka in Action seems to have completed at last! Congratulations!!

In the last chapter of this book, some experimental modules of Akka are described a little. Today, I tried one of them Akka Typed which makes a typed response.

Below is a simple example of replying message from normal actor:

import akka.actor._
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

object Hello {
final case class HelloMessage(name: String)
final case class HelloResult(message: String)

class HelloActor extends Actor {
def receive = {
case HelloMessage(name) => sender ! HelloResult(s"Hello $name!")
}
}
}

implicit val timeout = Timeout(5 seconds)

val system = ActorSystem("system")
val actor = system.actorOf(Props[Hello.HelloActor])
val f: Future[Any] = actor ? Hello.HelloMessage("Naoki")

f.mapTo[Hello.HelloResult].foreach { result =>
println(result.message)
}

Type of response from actor is Future[Any], so I have to cast it using mapTo method. It isn’t type-safe.

I would like to rewrite above using Akka Typed:

import akka.typed._
import akka.typed.ScalaDSL._
import akka.typed.AskPattern._
import akka.util.Timeout
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

object TypedHello {
final case class HelloMessage(name: String, replyTo: ActorRef[HelloResult])
final case class HelloResult(message: String)

val helloBahavior = ContextAware[HelloMessage] { ctx =>
Static {
case HelloMessage(name, replyTo) => replyTo ! HelloResult(s"Hello $name!")
}
}
}

implicit val timeout = Timeout(5 seconds)

val system: ActorSystem[TypedHello.HelloMessage] = ActorSystem("system", Props(TypedHello.helloBahavior))
val f: Future[Hello.HelloResult] = system ? (TypedHello.HelloMessage("Naoki", _: ActorRef[TypedHello.HelloResult]))

f.foreach { result =>
println(result.message)
}

Process was moved to ContextAware from Actor. Sent message has typed ActorRef which receives a response message. Some Akka’s major APIs such as ActorSystem, ActorRef and ? method got type-safe interface by replaced by Akka Typed’s one.

Note that Akka Typed is still experimental and Akka in Action is also saying:

The akka-typed API looks promising, but is highly likely to change since it hasn’t been pushed to its limits yet by anyone, and right now it shouldn’t be used in production. The benefits of types are huge, so we expect the module to become very important in upcoming versions of Akka.

Anyway, Akka in Action is a good book to learn Akka and design of Akka based application. I highly recommend it. Thanks the authors for their great work!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.