Need an example of how to use flatMapPrefix in akka stream

Viewed 59

I think i need that method but i am not sure how it works. Can someone give an example of its usage.

 def flatMapPrefix[Out2, Mat2](n: Int)(f: immutable.Seq[Out] => Flow[Out, Out2, Mat2]): Repr[Out2] = {
    via(new FlatMapPrefix(n, f))
  }

are the n first elements processed pass downstream too ? or only those coming after ?

1 Answers

Only the elements coming later are passed to the flow created in the flatMapPrefix.

This will print 1 to 10:

Source(1 to 10)
    .runForeach(i => println(i))

Here we introduce a Flow that does nothing, so it will also print 1 to 10

  Source(1 to 10)
    .via(Flow[Int])
    .runForeach(i => println(i))

Here we use first 5 elements to create a Flow that will process the rest of the elements so it will print 6 to 10:

  Source(1 to 10)
    .flatMapPrefix(5) { l =>
      Flow[Int]
    }
    .runForeach(i => println(i))

Though we can still get those elements by using prepend. This prints 1 to 10:

  Source(1 to 10)
    .via(Flow[Int])
    .flatMapPrefix(5) { l =>
      Flow[Int]
        .prepend(Source(l))
    }
    .runForeach(i => println(i))
Related