Search code examples
scalaterminateakka-stream

How to end an infinite akka stream


I'm new to Akka Streams but have a case where I want to use it to look for permutations from an infinite source. A simplified example with a finite source could look like this.

val future = Source(1 to 100)
    .map { i => if (i % 20 == 0) println(i); i }
    .filter(_ == 42)
    .runWith(Sink.fold[Int, Int](0)(Keep.right))

This exemple outputs:

20
40
60
80
100

I'm obviously fine with the source getting past 42 but I don't want to exhaust the entire stream before being able to get the result.

val result: Int = Await.result(future, 1.second)
result should be(42)

Question is, how should I end the stream when I've found what I'm looking for?


Solution

  • val future = Source(1 to 100)
        .map { i => if (i % 20 == 0) println(i); i }
        .filter(_ == 42)
        .runWith(Sink.head)