Creating Actor in Akka



In Scala, we can create an Actor by extending the akka.actor.Actor class and writing the receive method in that class. Normally we will write the receive method by using the case statement that will allow the actor to respond t the different type of the messages it receives.

lets first create a project using the SBT name HelloAkka. Let's define our necessary resolver and dependency resolver information in the build.sbt file which looks like this.

name := "HelloAkka"

version := "1.0"

scalaVersion := "2.12.1"

resolvers += "Typesage Repository" at
    "http://repo.typesafe.com/typesage/releases/"

libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.4.12"

if you are new to sbt don't worry it just like a maven or gradle which is esp build for scala and with much more features

Now lets write our first HelloAkka class

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

/**
  * Created by yubrajpokharel on 12/10/17.
  */
class HelloActor extends Actor{
  override def receive = {
    case "hello" => println("hello message is received")
    case _ => println("Opps I think I missed it..")
  }
}

object main extends App{

  //creating a actor system
  val system = ActorSystem("helloworld")

  //creating and starting an actor system
  val helloActor = system.actorOf(Props[HelloActor], name="helloActor")

  //sending message to an actor
  helloActor ! "hello"
  helloActor ! "namaste" //namaste is a nepali/hindi word for the greeting like hello/hi ;)

  //shutting down the actor system
  system.shutdown
}


save this class as HelloActor.scala and run with sbt run then you will get the following output

[info] Running main 
hello message is received
Opps I think I missed it..
  1. Now let's discuss what we did exactly
  2. The actor named HelloActor is defined which behavior is defined by the overridden receive method
  3. We implemented the receive method using the match expression (switch in Java)
  4. based on the message received out actor print the hello message is received on receiving the hello message and another when the message is other than hello
  5. We created a Main object which is required to test the actor. For the actor based system, we need to define the ActorSystem which takes the name and the property to start the actor system
  6. We created the actor system using the system.actorof method. 
  7. Actors are automatically started asynchronously when we call actorOf method, we don't need to call any start or run method here.
  8. Messages are sent to actors by using the ! method
  9. helloActor responds to the actors by executing the println statements
  10. The actor system is shutdown using the shutdown method.

Comments

Popular posts from this blog

Functional Programming in Java - Part 1

Communication between two Actor's In scala

Stopping the Actor in Akka