Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Source from Future[Iterator]?

I have a Future[Iterator]. I want to feed this iterator to my Stream. Here, I still want to construct a Source from the Iterator like we do using Source.fromIterator.

But, I can't use Source.fromIterator here due to Future.

Maybe I could use Source.fromFuture but I when I try to use it, it doesn't seem to actually create a Source from the Iterator in my case. From the docs:

/**
   * Starts a new `Source` from the given `Future`. The stream will consist of
   * one element when the `Future` is completed with a successful value, which
   * may happen before or after materializing the `Flow`.
   * The stream terminates with a failure if the `Future` is completed with a failure.
   */
  def fromFuture[T](future: Future[T]): Source[T, NotUsed] =
    fromGraph(new FutureSource(future))
like image 410
oblivion Avatar asked May 17 '26 18:05

oblivion


1 Answers

You could use a combination of Source.fromFuture, flatMapConcat, and Source.fromIterator. For example:

val futIter = Future(Iterator(1, 2, 3))

val source: Source[Int, _] =
  Source.fromFuture(futIter).flatMapConcat(iter => Source.fromIterator(() => iter))
like image 104
Jeffrey Chung Avatar answered May 20 '26 13:05

Jeffrey Chung