Search code examples
ziosttpzio-streams

How to create ZStream of String from ZStream of Byte


I need to read file from http. I'm using sttp with ZioBackend like this:

val sttpBackend: SttpBackend[Task, ZioStreams] = ???

val request =
  basicRequest
    .post(uri"...")
    .response(asStreamUnsafe(ZioStreams))
    .readTimeout(Duration.Inf)

val response: ZIO[
  Any, 
  Throwable, 
  Response[Either[String, Stream[Throwable, Byte]]]
] = sttpBackend.send(request)

How to go from Stream[Throwable, Byte] to Stream[Throwable, String] in which each string would be a line from response body?


Solution

  • The way to go is to use ZTransducer in zio1.x:

      def decodeLines: ZTransducer[Any, Nothing, Byte, String] =
        ZTransducer.utf8Decode >>> ZTransducer.splitLines
    
      stream.transduce(decodeLines)
    

    Or in zio2.x via ZPipeline:

    stream.via(ZPipeline.utf8Decode >>> ZPipeline.splitLines)