collectFirst
Transform this stream by applying the given partial function to the first element on which the function is defined as it pass through this processing step, and cancel the upstream publisher after the first element is emitted.
Signature
Source.collectFirst
Source.collectFirst
Flow.collectFirst
Flow.collectFirst
Description
Transform this stream by applying the given partial function to the first element on which the function is defined as it pass through this processing step, and cancel the upstream publisher after the first element is emitted.
Example
- Scala
-
source
Source(List(1, 3, 5, 7, 8, 9, 10)) .collectFirst { case elem if elem % 2 == 0 => elem } .runWith(Sink.foreach(println)) // expect prints output: // 8
- Java
-
source
Source.from(Arrays.asList(1, 3, 5, 7, 8, 9, 10)) .collectFirst( PFBuilder.<Integer, Integer>create() .match(Integer.class, i -> i % 2 == 0, i -> i) .build()) .runWith(Sink.foreach(System.out::println), system); // expect prints output: // 8
Reactive Streams semantics
emits when the provided partial function is defined for the first element
backpressures when the partial function is defined for the element and downstream backpressures
completes upstream completes or the first element is emitted
cancels when downstream cancels