2
votes

I'm invoking a web service that returns an Option[Future[String]] inside an Akka actor. Now I need to spin a new child actor and pass this Option[Future[String]] and stop the actor.In the child actor I want to wait for the future to complete so that I can do something with the result. Is it okay to pass Futures around Akka actors?

1
My gut feeling is that, as long as they are on the same VM there shouldn't be a problem. Passing it to a remote actor, though, will probably cause problemsMario Camou
Yes, this is inside the same JVM. I feel the same but I want to confirm it.Soumya Simanta
Why not just call that future in the child actor? And actually you can use future.onComplete and other Future methods. Anyway, passing simple,immutable, serilizable message is always a good idea, if you really want pipe the result of future, you can use akka.pattern.pipe to pipe the result while future is completed.jilen
I'm quite sure futures are completely thread safe. You could even await their completion in 2 different threads at the same time. Although of course you shouldn't use await in an actor.SpiderPig
Another option might be to use an onSuccess callback on the Future and send the message to the other actor there. The other actor would then receive a String directly.Mario Camou

1 Answers

3
votes

Warning: Not compiled, see doc.akka.io if in doubt.

import akka.pattern.pipeTo
def receive = {
  case something =>
    webService.call() foreach { _ pipeTo context.actorOf(Props[Child]) }
}

The idea is that you do not need the child actor if the web service doesn't return anything (None), and if it returns Some(future) you send the result of that Future to the newly created child actor. The newly created child actor can then self-terminate once it receives the result of the webservice call.