Search code examples
scalazioscalaz-stream

Scala ZIO Stream -- Convert Stream[A] to Stream[B] where one A produces zero or more B


I have a Stream[A] and a function zeroOrMoreB(value: A): Seq[B] which given an A returns zero or more B. From these two pieces, how to I construct a Stream[B]?

I can get a Stream[Stream[B]] (see below), but I cannot figure out how to flatten it.

stream <- ZStream
  .fromIterable(vectorOfAs)
  .map(zeroOrMoreB)

Solution

  • As I always say, the Scaladoc is your friend.

    You can use mapConcat

    val stream = ZStream.fromIterable(vectorOfAs).mapConcat(zeroOrMoreB)
    

    Now if zeroOrMoreB actually returns a ZStream instead of a Seq, you just use flatMap

    val stream = ZStream.fromIterable(vectorOfAs).flatMap(zeroOrMoreB)
    

    Finally, if you like for syntax you can do this

    val stream = for {
      a <- ZStream.fromIterable(vectorOfAs)
      b <- ZStream.fromIterable(zeroOrMoreB(a))
    } yield b