Last active
April 22, 2020 14:31
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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