Communication between two Actor's In scala




In order to understand the commutation between two actors lets take an example of pingpong app which uses two actors name Ping and Pong.

import akka.actor._

/**
 * Created by yubrajpokharel on 12/11/17.
 */

case object PingMessage
case object PongMessage
case object StartMessage
case object StopMessage

class Ping(pong: ActorRef) extends Actor{
    var count = 0
    def incrementAndPrint {count+=1; println("ping")}
    override def receive = {
        case StartMessage =>
            incrementAndPrint
            pong ! PingMessage
        case PongMessage =>
            incrementAndPrint
            if(count > 90) {
                sender ! StopMessage
                println("ping stopped")
                context.stop(self)
            }else{
                sender ! PingMessage
            }
        case _ => println("ping got something unexpected")
    }
}

class Pong extends Actor{
    override def receive = {
        case PingMessage =>
            println(" pong")
            sender ! PongMessage
        case StopMessage =>
            println("pong stopped")
            context.stop(self)
        case _ => println("pong got something unexpected")
    }
}

object PingPong extends App{
    val system = ActorSystem("PingPongSystem")
    val pong = system.actorOf(Props[Pong], name = "ping")
    val ping = system.actorOf(Props(new Ping(pong)), name = "pong")
    ping ! StartMessage

    system.shutdown
}


What exactly is happening here, lets have a look 

initially, we create a 4 case object's name PingMessage, PongMessage, StartMessage, and StopMessage. [case objects are just like a singleton class in java with no args].then we create two Actor class named Ping and Pong. Here Ping class takes a Pong object as a reference which is initially an ActorRef.
then we send a StartMessage message to ping using the ! method. Once the ping receives the message it increments the count by one and bring the "ping" message and using the sender ref it sends back the PingMessage. Again when the Ping receives the message it evaluates it and brings the "pong" message. and send a message back to the sender. The ping actor now receives the PongMessage and now it will check the counter and if it's greater then 99 then it stops itself and send the SendMessage to the pong and the pong will also stop itself.


The output of the following example will be::

[info] Running PingPong 
ping
 pong
...
ping
 pong
ping
 pong
ping
 pong
ping
 pong
ping
[INFO] [12/11/2017 01:58:48.293] [PingPongSystem-akka.actor.default-dispatcher-6] 

Comments

Popular posts from this blog

Functional Programming in Java - Part 1

Stopping the Actor in Akka