Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Akka Cookbook

You're reading from   Akka Cookbook Recipes for concurrent, fast, and reactive applications

Arrow left icon
Product type Paperback
Published in May 2017
Publisher Packt
ISBN-13 9781785288180
Length 414 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Authors (3):
Arrow left icon
Vivek Mishra Vivek Mishra
Author Profile Icon Vivek Mishra
Vivek Mishra
Piyush Mishra Piyush Mishra
Author Profile Icon Piyush Mishra
Piyush Mishra
Héctor Veiga Ortiz Héctor Veiga Ortiz
Author Profile Icon Héctor Veiga Ortiz
Héctor Veiga Ortiz
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Diving into Akka FREE CHAPTER 2. Supervision and Monitoring 3. Routing Messages 4. Using Futures and Agents 5. Scheduling Actors and Other Utilities 6. Akka Persistence 7. Remoting and Akka Clustering 8. Akka Streams 9. Akka HTTP 10. Understanding Various Akka patterns 11. Microservices with Lagom

Asking for a result from an actor

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.

How to do it...

Let's define an actor that computes something, say, the Fibonacci of a number:

  1. Create a Scala file, FibonacciActor.scala, in the package com.packt.chapter1.
  2. 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 )
}
}
  1. 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.

  1. Create an application which asks for result from the actor.
  2. 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._
  1. 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)
}
  1. Run the preceding application in the IDE-like intelliJ Idea or from the console, and you will get the following output:

How it works...

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.

There's more...

You have been reading a chapter from
Akka Cookbook
Published in: May 2017
Publisher: Packt
ISBN-13: 9781785288180
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image