In this recipe, we will ask the actor to give us the result that it computes. Prerequisites are the same as the previous recipes.
In the last recipe, you learnt how to send a message using the tell-and-forget pattern. In this recipe, you will learn how to get the result from an actor after it does something.
Let's define an actor that computes something, say, the Fibonacci of a number:
- Create a Scala file,
FibonacciActor.scala
, in the packagecom.packt.chapter1
. - Add import to the top of the file:
import akka.actor.Actor
Now we define an actor which computes the Fibonacci of a number:
class FibonacciActor extends Actor { override def receive: Receive = { case num : Int => val fibonacciNumber = fib(num) } def fib( n : Int) : Int = n match { case 0 | 1 => n case _ => fib( n-1 ) + fib( n-2 ) } }
- As of now, we have defined the actor. To send the computed result back to the sender, we have to add one more line to the actor code:
sender ! fibonacciNumber
Now, notice the difference:
class FibonacciActor extends Actor { override def receive: Receive = { case num : Int => val fibonacciNumber = fib(num) sender ! fibonacciNumber } def fib( n : Int) : Int = n match { case 0 | 1 => n case _ => fib( n-1 ) + fib( n-2 ) } }
Actors, by their implementation, know the default immediate sender, that is, they know who has sent them the message.
- Create an application which asks for result from the actor.
- Add the following imports to the top of file:
import akka.actor.{Props, ActorSystem} import akka.pattern.ask import akka.util.Timeout import scala.concurrent.Await import scala.concurrent.duration._
- Create an object,
FibonacciActorApp
as follows:
object FibonacciActorApp extends App { implicit val timeout = Timeout(10 seconds) val actorSystem = ActorSystem("HelloAkka") val actor = actorSystem.actorOf(Props[FibonacciActor]) // asking for result from actor val future = (actor ? 10).mapTo[Int] val fiboacciNumber = Await.result(future, 10 seconds) println(fiboacciNumber) }
- Run the preceding application in the IDE-like intelliJ Idea or from the console, and you will get the following output:
We create an actor that computes Fibonacci number, and sends the result to the sender who sent him the message to compute the Fibonacci.
In the actor receive block, we send the Fibonacci result back to the sender. Actors, by nature, know who has sent them the message, thus we always have the sender present in the context of the receive block.
When you send a message to the actor using a question mark (?
), it returns a future promising that you will get the result when the operation would be completed.
We will learn about futures in later chapters.
To know more about sending messages to actors, go to the following link:
http://doc.akka.io/docs/akka/current/scala/actors.html#Send_messages.