Search code examples
scalaakkaakka-stream

How to create an Akka Stream Flow that pauses until a flag is lowered?


I want to create an Akka Streams Flow that will consume an element and hold it until a Flag is lowered.

The desired effect is illustrated below but I realise that this not a good solution.

val flow: Flow[Int, Int, NotUsed] = {
     Flow[Int] map { i =>
       if (flagIsRaised) { waitUntilFlagIsLowered(); i}
       else { i }
     }
}

For example, I don't want waitUntilFlagIsLowered to block.

Ideally, I would like an idiomatic Akka Streams solution that might be possible using standard Akka Streams operators.


Solution

  • Check out the Valve utility from the Akka Streams Contrib project:

    Materializes into a Future of ValveSwitch which provides a the method flip that stops or restarts the flow of elements passing through the stage. As long as the valve is closed it will backpressure.

    Examples of how to use it are in ValveSpec.