Search code examples
scalaakkaakka-streamakka-http

Akka flow for multiple http requests


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 = {
    Json.obj(
      "to" -> id,
      "priority" -> "high",
      "data" -> Json.obj("message" -> "Firebase Clud Message"),
      "time_to_live" -> 60
    ).toString()
  }

  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]] = {
    Http().outgoingConnection("fcm.googleapis.com")
  }

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

    val httpRequests: List[HttpRequest] = ids.map(buildBody).map(buildHttpRequest)
    println(httpRequests)

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

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

  }
}

Solution

  • 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 =>
      response.discardEntityBytes()
      println(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 }
      .map(println(_))
    }