Sink.forall
A Sink
that will test the given predicate p
for every received element and completes with the result.
Signature
Description
forall applies a predicate function to assert each element received, it returns true if all elements satisfy the assertion, otherwise it returns false.
It materializes into a Future
(in Scala) or a CompletionStage
(in Java) that completes with the last state when the stream has finished.
Notes that if source is empty, it will return true
A Sink
that will test the given predicate p
for every received element and
- completes and returns
Future
CompletionStage
oftrue
if the predicate is true for all elements; - completes and returns
Future
CompletionStage
oftrue
if the stream is empty (i.e. completes before signalling any elements); - completes and returns
Future
CompletionStage
offalse
if the predicate is false for any element.
The materialized value Future
CompletionStage
will be completed with the value true
or false
when the input stream ends, or completed with Failure
if there is a failure signaled in the stream.
Example
This example tests all elements in the stream is <=
100.
- Scala
-
source
val result: Future[Boolean] = Source(1 to 100) .runWith(Sink.forall(_ <= 100)) val allMatch = Await.result(result, 3.seconds) println(allMatch) // Expect prints: // true
- Java
-
source
final boolean allMatch = Source.range(1, 100) .runWith(Sink.forall(elem -> elem <= 100), system) .toCompletableFuture() .get(3, TimeUnit.SECONDS); System.out.println(allMatch); // Expect prints: // true
Reactive Streams Semantics
Completes when upstream completes or the predicate p
returns false
cancels when predicate p
returns false
backpressures when the invocation of predicate p
has not yet completed