Sink.exists

A Sink that will test the given predicate p for every received element and completes with the result.

Sink operators

Signature

Sink.existsSink.exists

Description

exists applies a predicate function to assert each element received, it returns true if any 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 false

A Sink that will test the given predicate p for every received element and

  • completes and returns Future CompletionStage of true if the predicate is true for any element;
  • completes and returns Future CompletionStage of false if the stream is empty (i.e. completes before signalling any elements);
  • completes and returns Future CompletionStage of false if the predicate is false for all elements.

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 any element in the stream is > 3.

Scala
sourceval result = Source(1 to 4)
  .runWith(Sink.exists(_ > 3))
val anyMatch = Await.result(result, 3.seconds)
println(anyMatch)
// Expect prints:
// true
Java
sourcefinal boolean anyMatch =
    Source.range(1, 4)
        .runWith(Sink.exists(elem -> elem > 3), system)
        .toCompletableFuture()
        .get(3, TimeUnit.SECONDS);
System.out.println(anyMatch);
// Expected prints:
// true

Reactive Streams Semantics

Completes when upstream completes or the predicate p returns true

cancels when predicate p returns true

backpressures when the invocation of predicate p has not yet completed