Beginners Level: Akka Typed API

Reading Time: 3 minutes
Beginner Level: Akka Typed API

In this blog, I will be explaining Akka Typed API. This is going to be my first blog on Akka Typed, so let us name it “Beginner Level: Akka Typed API“. Here, I will be telling you the reason for preferring Akka typed over untyped. Along with that, I will also be demonstrating some implementations with Akka Typed.

Now before heading towards Akka Typed API, it’s important to first discuss Akka untyped. Basically in Akka untyped, we don’t know the type of messages that we are passing. The worst thing about Akka untyped is the receive() method of Akka untyped actor that accepts anything and returns nothing. The type of receive() method of Akka untyped API is PartialFraction[Any, Unit] which takes Any as an input and returns Unit as an output.

That is the moment Akka typed comes into the picture and solves the problem. It provides the type of incoming and outgoing messages.

Here, first of all, we will show the implementation of untyped actor and then move towards the typed Akka .

The first thing to do is to quickly add the library dependencies for typed and untyped Akka in build.sbt file . As a result of which, our build.sbt will look like:

name := "Akka-actor-Demo"
version := "0.1"
scalaVersion := "2.13.5"
libraryDependencies ++=Seq( "com.typesafe.akka" %% "akka-actor" % "2.6.13",
                        "com.typesafe.akka" %% "akka-actor-typed" % "2.6.14")

Now let us create an actor which handles messages. We will extend the Actor trait and override receive method in Akka untyped API to create this actor.

import akka.actor.{Actor, ActorSystem, Props}

object Hotel extends App
{
  case class BookRoom(roomType : String)
  case object RoomBooked

  case class BookRoomWithFood(foodAmount : Long)
  case object RoomBookedWithFood

  val system = ActorSystem("hotel")
  val hotelActor = system.actorOf(Props[HotelActor],"hotelActor")
  hotelActor ! BookRoomWithFood(500)

}

class HotelActor extends Actor
{
  import Hotel._
  def receive: Receive = {
    case BookRoom("AC Room") => println("Book Ac room")
    case RoomBooked => println("Room Booked ")

    case BookRoomWithFood(500) => println("Book Room with Food ")
    case RoomBookedWithFood => println("Room Booked ")
  }
}

Here in the above code, we can clearly see that the actor can handle messages of Any type it wants. Thus, we can send and receive any type of message here.

Now let us talk about Akka typed API which provides type to incoming and outgoing messages.

In Actor typed API

There is no receive() method, no Actor trait, no Props, and no more implicit sender ( sender() ) or Actor Selection.

ActorRef is typed i.e. ActorRef[T] where T is the type.

Instead of extending Actors, define Behaviour[T].

Implementing Akka Typed

Now, let us implement the above example using Akka typed API. For that, we need to define a behavior that must be enough for creating an actor using typed API. Behavior contains many factory methods e.g. same, receive message, setup, receive signal, etc.

import akka.actor.typed.scaladsl.Behaviors
import akka.actor.typed.{ActorRef, ActorSystem, Behavior}

object HotelTyped
{
  //incoming messages need to extend commands
  sealed trait Command
  case class BookRoom(roomType : String , replyTo : ActorRef[RoomBooked]) extends Command
  case class RoomBooked()

  case class BookRoomWithFood(foodAmount : Long,replyTo : ActorRef[RoomBookedWithFood]) extends Command
  case class RoomBookedWithFood()

  def apply() : Behavior[Command]={
    Behaviors.receiveMessage{
      case BookRoom("AC" , replyTo) =>
        replyTo ! RoomBooked()
        Behaviors.same

      case BookRoomWithFood(500,replyTo) =>
        replyTo ! RoomBookedWithFood()
        Behaviors.same
        //if behaviour of next msg has to change then only change it .
    }
  }

}

In the above code, as you can see, the protocols are defined as a sealed trait. This is to make the compiler warn us in case we are doing any mistakes while sending and receiving messages that do not belong to the protocol.

The typed actor needs a function (that applies in this case) to construct a behaviour using the protocol we created. Also as you can see to keep the behaviour same we have to return Behaviour.same .This is how we create actors using Akka typed API.

To conclude, this was just a quick elementary glimpse of Typed Actors. It appears very intuitive and the fact that the requests and responses both can be typed will most likely result in formulating more secure codes. I found it a remarkably delicate way of creating actor systems among all.

Reference

Akka Typed Documentation

Written by 

Utkarsh Upadhyay is a Software Consultant at Knoldus Software LLP, having experience of more than 2 years. He has done B. Tech from IMS Engineering College, Ghaziabad. He has a decent knowledge of Scala, Lagom, Kafka, Cassandra, Akka, and Akka Stream. He loves playing and watching cricket and exploring new places.

1 thought on “Beginners Level: Akka Typed API4 min read

Comments are closed.