How to convert a Stream[IO, List[A]] to Stream[IO, A]
Asked Answered
F

2

6

I want to parse a json file which output a collection of A. The signature of the Output is IO[List[A]]

How can I convert this value to a Stream: Stream[IO, A] ? I can convert to a Stream[IO, List[A]] but it is not what I want

fs2.Stream.eval(input).flatMap(x => fs2.Stream.apply(x)) Thanks

Fosque answered 10/4, 2018 at 10:39 Comment(0)
L
4

Try

fs2.Stream.eval(output).flatMap(x => fs2.Stream.apply(x: _*))

What does `:_*` (colon underscore star) do in Scala?

Lordly answered 10/4, 2018 at 12:11 Comment(0)
E
13

You can also use Stream.emits, which accepts a Seq, so fs2.Stream.eval(output).flatMap(fs2.Stream.emits(_)).

This is more efficient than using varargs with apply because it avoids wrapping and unwrapping the sequence structure - this can save a lot in the case of specialized primitive collections.

Edit: As of more recent fs2 versions (3.9.x as I write this) there's a convenience method for this now

def input: IO[List[Foo]] = ???
fs2.Stream.evalSeq(input) // Stream[IO, Foo]
Equator answered 19/6, 2018 at 19:55 Comment(1)
Thank you so much! I was getting annoyed with the amount of vararg conversions I was dealing with. This is much cleanerFrazer
L
4

Try

fs2.Stream.eval(output).flatMap(x => fs2.Stream.apply(x: _*))

What does `:_*` (colon underscore star) do in Scala?

Lordly answered 10/4, 2018 at 12:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.