Question: Akka flow for multiple http requests


Akka flow for multiple http requests

Answers 1
Added at 2016-12-30 15:12

In a project of mine I have an akka actor for sending post requests to my google fcm server. The actor takes a list of ids and should make as many requests as there are in the list. I print out the response from the server in runForeach(println(_)) but I only get one printout for a whole list of ids. Why does this happen?

class FCMActor(val key: String) extends Actor{
  import fcm.FCMActor._
  import akka.pattern.pipe
  import context.dispatcher

  private implicit def system: ActorSystem = ActorSystem()
  final implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system))

  def buildBody(id: Option[String]): String = {
      "to" -> id,
      "priority" -> "high",
      "data" -> Json.obj("message" -> "Firebase Clud Message"),
      "time_to_live" -> 60

  def buildHttpRequest(body: String): HttpRequest = {
    HttpRequest(method = HttpMethods.POST,
      uri = s"/fcm/send",
      entity = HttpEntity(MediaTypes.`application/json`, body),
      headers = List(RawHeader("Authorization", s"key=$key")))

  val connectionFlow: Flow[HttpRequest, HttpResponse, Future[Http.OutgoingConnection]] = {

  def send(ids: List[Option[String]]) = {

    val httpRequests: List[HttpRequest] =

    Source(httpRequests).via(connectionFlow).runForeach(println(_)) // << here I only get one println

  override def receive: Receive = {
    case SendToIds(ids: List[Option[String]]) =>

Answers to

Akka flow for multiple http requests

nr: #1 dodano: 2016-12-30 17:12

You are not consuming the response entity that the server sends you. To understand why this is important, check out the related docs page.

A quick code change to try and fix this is:

... .runForeach{ response =>

Or, if you're actually interested in the entity, something along the lines of

... .runForeach{ _.entity.dataBytes
  .runFold(ByteString.empty) { case (acc, b) => acc ++ b }
Source Show
◀ Wstecz