Akka akka / scala - single onSuccess for multiple requests
I have a chain of akka actors like
A --> B --> C
Actor A asks Actor B, who in turn "asks" Actor C. Actor A needs to wait until Actor C finishes processing. B is a thin layer and does nothing but send (request) a message to C and return the future back to A. Basically B just does
{ case msgFromA => sender ! C ? msgFromA }
Therefore, what A gets is the Future [Any].
The way to handle the request is to use nested maps
actorRefFactory.actorOf(Props[A]) ? msgA map {
resp =>
// Type cast Any to Future and use another map to complete processing.
resp.asInstanceOf[Future[_]] map {
case Success =>
// Complete processing
case Failure(exc) =>
// Log error
This works (i.e., final processing only occurs when the C actor has finished processing), but of course it looks terrible. I tried using flatmaps but couldn't get it to work. Any ideas to make it look good :) Thanks
source to share
A more correct way:
In A
:
val f: Future[MyType] = (B ? msg).mapTo[MyType]
f onComplete {
case Success(res) => // do something
case Failure(t) => // do something
}
In B
use forward
:
{ case msgFromA => C forward msgFromA }
In C
:
// call database
// update cache
sender() ! res // actually sends to A
source to share