Skip to content

Instantly share code, notes, and snippets.

@nightscape
Last active April 22, 2020 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nightscape/1b7fc3e28815c40f536397eea073fa4b to your computer and use it in GitHub Desktop.
Save nightscape/1b7fc3e28815c40f536397eea073fa4b to your computer and use it in GitHub Desktop.
Http4s: Stream a constant String until the response is ready (might be useful for preventing connection to be closed)
def constantStringThenContent[F[_] : Timer : Concurrent, A](constantString: String, result: F[A])(
implicit W: EntityEncoder[F, A]
): Response[F] = {
val resultStream = Stream.eval(result)
val preStream = EntityEncoder.stringEncoder[F].toEntity(constantString).body
val composedStream = (Stream[F, Option[A]](None, None, None) ++ resultStream.map(Option.apply))
.switchMap[F, Byte] {
case None =>
fs2.Stream.awakeEvery[F](10.second).flatMap(_ => preStream)
case Some(v) => W.toEntity(v).body
}
val headers =
W.headers.get(`Transfer-Encoding`) match {
case Some(transferCoding) if transferCoding.hasChunked =>
W.headers
case _ =>
W.headers.put(`Transfer-Encoding`(TransferCoding.chunked))
}
Response(status = Status.Ok, headers = headers, body = composedStream)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment