Randomize Randomize - 4 months ago 40
Scala Question

Akka-Http: How to use an Actor in a request?

Based on this simple code for Akka-HTTP:

val route =
pathPrefix("myapp") {
path("search") {
get {
//ref ! DoSomething("foo")
complete(HttpEntity(ContentTypes.`application/json`, /* content here from an actor */ ))
}
}
}


How can I return a value from an Actor (
sender ! content
) ?

Answer

Use ask pattern and map it's return future.

import akka.pattern.ask    // enable `?`
import context.dispatcher  // Future's need an execution context, we use the Actor#context's one 

(ref ? DoSomething("foo")).mapTo[ReturningType].map { result =>
  complete(HttpEntity(ContentTypes.`application/json`, result ))
}