Using futures inside actors
We will learn how to use a future inside an actor to schedule an operation asynchronously to another thread.
Getting ready
All the prerequisites are the same as earlier; just import the Hello-Akka
project in the IDE.
How to do it...
The following are the steps to use future inside the actor:
- Create a scala file, say
FutureInsideActor.scala
, in thecom.packt.chapter4
package. - Add the following import to the top of the file:
import akka.actor.{Props, ActorSystem, Actor} import scala.concurrent.{Await, Future} import scala.concurrent.duration._
- Create an actor that uses a future inside, as shown in the following code snippet:
class FutureActor extends Actor { import context.dispatcher def receive = { case (a:Int, b:Int) => val f = Future(a+b) (Await.result(f, 10 seconds)) } }
- Create a test application, as follows:
object FutureInsideActor extends App { ...