Search code examples
scalaakkaakka-stream

Akka-stream, trigger action once I received a number of items?


I am looking for an "aggregator" block in akka-streams. For instance a block that waits until it has received 3 strings and then triggers an action - like evaluating the average length - and propagate downstream the result of the action.

The flow would wait to receive three strings, say

"hallo"
"boat"
"cat"

then evaluate the average length

4

and send it downstream. What's the easiest way to achieve this?


Solution

  • It depends on requirement but in your particular case you can do

    Source(List(1, 2, 3, 4, 5, 6, 7))
      .grouped(3)
      .map { chunk =>
        chunk.sum / 3.0
      }
    

    You can do variation of this using .scan as well.