August 2013
Intermediate to advanced
720 pages
16h 23m
English
You have one actor that needs to ask another actor for some information, and needs an immediate reply. (The first actor can’t continue without the information from the second actor.)
Use the ? or ask methods to send a message to an Akka actor
and wait for a reply, as demonstrated in the following
example:
importakka.actor._importakka.pattern.askimportakka.util.Timeoutimportscala.concurrent.{Await,ExecutionContext,Future}importscala.concurrent.duration._importscala.language.postfixOpscaseobjectAskNameMessageclassTestActorextendsActor{defreceive={caseAskNameMessage=>// respond to the 'ask' requestsender!"Fred"case_=>println("that was unexpected")}}objectAskTestextendsApp{// create the system and actorvalsystem=ActorSystem("AskTestSystem")valmyActor=system.actorOf(Props[TestActor],name="myActor")// (1) this is one way to "ask" another actor for informationimplicitvaltimeout=Timeout(5seconds)valfuture=myActor?AskNameMessagevalresult=Await.result(future,timeout.duration).asInstanceOf[String]println(result)// (2) a slightly different way to ask another actor for informationvalfuture2:Future[String]=ask(myActor,AskNameMessage).mapTo[String]valresult2=Await.result(future2,1second)println(result2)system.shutdown}
Both the ? or ask methods use the Future and Await.result approach demonstrated in Recipe 13.9. The recipe ...
Read now
Unlock full access