Execution Context for Actor Futures

I have an actor, and in some post I run some method that returns Future.

def receive: Receive = { case SimpleMessge() => val futData:Future[Int] = ... futData.map { data => ... } } 

Is it possible to convey the real context for waiting for this data? Or is Await the best I can do if I need this data in SimpleMessage?

+7
scala future actor akka
source share
1 answer

If you really need to wait for the future to finish before processing the next message, you can try something like this:

 object SimpleMessageHandler{ case class SimpleMessage() case class FinishSimpleMessage(i:Int) } class SimpleMessageHandler extends Actor with Stash{ import SimpleMessageHandler._ import context._ import akka.pattern.pipe def receive = waitingForMessage def waitingForMessage: Receive = { case SimpleMessage() => val futData:Future[Int] = ... futData.map(FinishSimpleMessage(_)) pipeTo self context.become(waitingToFinish(sender)) } def waitingToFinish(originalSender:ActorRef):Receive = { case SimpleMessage() => stash() case FinishSimpleMessage(i) => //Do whatever you need to do to finish here ... unstashAll() context.become(waitingForMessage) case Status.Failure(ex) => //log error here unstashAll() context.become(waitingForMessage) } } 

In this approach, we process SimpleMessage and then switch the processing logic so that all subsequent SimpleMessage are retrieved until we get the result from the future. When we get a result, failure or not, we swing all the rest of SimpleMessage , which we received in anticipation of the future, and continue our fun journey.

This actor simply switches between the two states and allows you to fully process only one SimpleMessage at a time without having to block the future.

+10
source share

All Articles