Skip to content

Instantly share code, notes, and snippets.

@nraychaudhuri
Last active April 19, 2018 09:23
Show Gist options
  • Save nraychaudhuri/9381621 to your computer and use it in GitHub Desktop.
Save nraychaudhuri/9381621 to your computer and use it in GitHub Desktop.
Returning Play response from Akka actors without using ask
package controllers
import play.api.mvc._
import scala.concurrent._
import akka.actor.{Props, Actor}
import play.api.Play.current
import play.api.libs.concurrent.Akka
import scala.concurrent.ExecutionContext.Implicits._
object Application extends Controller {
val computeActor = Akka.system.actorOf(Props[BizActor])
def index = Action.async {
//using Promise as a write handle for the response from actor.
//we will use this promise to create a future (read handle)
//which will be returned from this action. This future will complete
//when the promise is successfully populated with value
val p = Promise[String]
val replyTo = Akka.system.actorOf(Props(new Actor {
def receive = {
case reply: String =>
p.success(reply)
context.stop(self)
}
}))
computeActor.tell(msg = "do work for me", sender = replyTo)
//transforming the actor response to Play result
p.future.map(response => Ok(response))
}
}
class BizActor extends Actor {
def receive = {
case _ => sender ! "I am done with work"
}
}
@iamanandkris
Copy link

Hello Nilanjan
I have a question on the above code
Will the usage of a Promise allocate a separate thread for its processing (like how its for a Future)? If that is the case, this code will allocate a thread per user request (to the index operation) right? Could you please explain a bit on that?
Thank you
Anand

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment