I have a list of Integers {2,4,6,8,9,10,12}
To simplify my problem, My goal is to get all even integers until I encounter an odd number. So my result should be -> {2,4,6,8, 9}
Also, i have an actor that says if a number is even or odd (for simplicity)
I have done the following :-
CompletionStage<List<Integer>> result = Source.from(integerList)
.ask(oddEvenActor, OddEvenResponse.class, Timeout.apply(1, TimeUnit.SECONDS))
.map(oddEvenResult -> if(oddEvenResult.isOdd()){
//stop processing further elements
}
else {
return oddEvenResult.number();
})
.runWith(Sink.seq(), materializer)
So how can i stop the proceessing of further elements as soon as i encounter an odd element?
The CompletionStage "result" should contain 2,4,6,8,9 once the stream is complete.
I checked out the statefulMapConcat (https://doc.akka.io/docs/akka/current/stream/operators/Source-or-Flow/statefulMapConcat.html) However, this will still process the other elements after 9 as the actor will still be "asked"
Of course I can do the following :-
Have a resultList variable (global) and i do a resultList.add(oddEvenResult.number()) and then Throw an exception once i encounter odd number. I have to write a custom exception class to piggy back this global resultList.
Use takeWhile as suggested by @Jeffrey Chung, but the OddEvenActoor is still "asked" to process elements 10 and 12. This is pointless.
Is there a cleaner way to achieve this?