Class Sink<In,Mat>
A Sink is a set of stream processing steps that has one open input.
Can be used as a Subscriber
-
Nested Class Summary
Nested classes/interfaces inherited from interface org.apache.pekko.stream.Graph
Graph.GraphMapMatVal<S extends Shape,M> -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionSends the elements of the stream to the givenActorRef.actorRefWithBackpressure(ActorRef ref, Object onInitMessage, Object ackMessage, Object onCompleteMessage, Function<Throwable, Object> onFailureMessage) Sends the elements of the stream to the givenActorRefthat sends back back-pressure signal.actorRefWithBackpressure(ActorRef ref, Object onInitMessage, Object onCompleteMessage, Function<Throwable, Object> onFailureMessage) Sends the elements of the stream to the givenActorRefthat sends back back-pressure signal.addAttributes(Attributes attr) Add the given attributes to thisSink.static <T> Sink<T,org.reactivestreams.Publisher<T>> asPublisher(AsPublisher fanout) ASinkthat materializes into aPublisher.asScala()Converts this Sink to its Scala DSL counterpart.async()Put an asynchronous boundary around thisSinkPut an asynchronous boundary around thisSinkPut an asynchronous boundary around thisSinkASinkthat immediately cancels its upstream after materialization.static <U,In> Sink<In, CompletionStage<U>> Creates a sink which materializes into aCompletionStagewhich will be completed with a result of the JavaCollectortransformation and reduction operations.combine(List<? extends Graph<SinkShape<U>, M>> sinks, Function<Integer, Graph<UniformFanOutShape<T, U>, NotUsed>> fanOutStrategy) Combine several sinks with fan-out strategy likeBroadcastorBalanceand returnsSink.combine(Sink<U, ?> output1, Sink<U, ?> output2, List<Sink<U, ?>> rest, Function<Integer, Graph<UniformFanOutShape<T, U>, NotUsed>> fanOutStrategy) Combine several sinks with fan-out strategy likeBroadcastorBalanceand returnsSink.static <T,U, M1, M2, M>
Sink<T,M> combineMat(Sink<U, M1> first, Sink<U, M2> second, Function<Integer, Graph<UniformFanOutShape<T, U>, NotUsed>> fanOutStrategy, Function2<M1, M2, M> matF) Combine two sinks with fan-out strategy likeBroadcastorBalanceand returnsSinkwith 2 outlets.static <T,M> Sink<T, CompletionStage<M>> completionStageSink(CompletionStage<Sink<T, M>> future) Turn aFuture[Sink]into a Sink that will consume the values of the source when the future completes successfully.Transform this Sink by applying a function to each *incoming* upstream element before it is passed to theSinkstatic <In> Sink<In,CompletionStage<Long>> count()ASinkthat counts all incoming elements until upstream terminates.static <In> Sink<In,CompletionStage<Boolean>> ASinkthat will test the given predicatepfor every received element and 1.static <U,In> Sink<In, CompletionStage<U>> ASinkthat will invoke the given function for every received element, giving it its previous output (or the givenzerovalue) and the element as input.static <U,In> Sink<In, CompletionStage<U>> foldAsync(U zero, Function2<U, In, CompletionStage<U>> f) ASinkthat will invoke the given asynchronous function for every received element, giving it its previous output (or the givenzerovalue) and the element as input.static <U,In> Sink<In, CompletionStage<U>> ASinkthat will invoke the given function for every received element, giving it its previous output (or the givenzerovalue) and the element as input.static <In> Sink<In,CompletionStage<Boolean>> ASinkthat will test the given predicatepfor every received element and 1.static <T> Sink<T,CompletionStage<Done>> ASinkthat will invoke the given procedure for each received element.static <T> Sink<T,CompletionStage<Done>> foreachAsync(int parallelism, Function<T, CompletionStage<Void>> f) ASinkthat will invoke the given procedure asynchronously for each received element.static <T,M> Sink<T, M> A graph with the shape of a sink logically is a sink, this method makes it so also in type.static <T,M> Sink<T, CompletionStage<M>> fromMaterializer(Function2<Materializer, Attributes, Sink<T, M>> factory) Defers the creation of aSinkuntil materialization.fromSubscriber(org.reactivestreams.Subscriber<In> subs) Helper to createSinkfromSubscriber.static <In> Sink<In,CompletionStage<In>> head()ASinkthat materializes into aCompletionStageof the first value received.static <In> Sink<In,CompletionStage<Optional<In>>> ASinkthat materializes into aCompletionStageof the optional first value received.static <T> Sink<T,CompletionStage<Done>> ignore()ASinkthat will consume the stream and discard the elements.static <In> Sink<In,CompletionStage<In>> last()ASinkthat materializes into aCompletionStageof the last value received.static <In> Sink<In,CompletionStage<Optional<In>>> ASinkthat materializes into aCompletionStageof the optional last value received.static <T,M> Sink<T, CompletionStage<M>> lazyCompletionStageSink(Creator<CompletionStage<Sink<T, M>>> create) Defers invoking thecreatefunction to create a future sink until there is a first element passed from upstream.static <T,M> Sink<T, CompletionStage<M>> Defers invoking thecreatefunction to create a sink until there is a first element passed from upstream.mapMaterializedValue(Function<Mat, Mat2> f) Transform only the materialized value of this Sink, leaving all other properties as they were.Add anameattribute to this Sink.static <T> Sink<T,CompletionStage<Done>> never()ASinkthat will always backpressure never cancel and never consume any elements from the stream.static <In> Sink<In,CompletionStage<Boolean>> ASinkthat will test the given predicatepfor every received element and 1.onComplete(Procedure<scala.util.Try<Done>> callback) ASinkthat when the flow is completed, either through a failure or normal completion, apply the provided function withSuccessorFailure.preMaterialize(ClassicActorSystemProvider systemProvider) Materializes this Sink, immediately returning (1) its materialized value, and (2) a new Sink that can be consume elements 'into' the pre-materialized one.preMaterialize(Materializer materializer) Materializes this Sink, immediately returning (1) its materialized value, and (2) a new Sink that can be consume elements 'into' the pre-materialized one.static <T> Sink<T,SinkQueueWithCancel<T>> queue()Creates aSinkthat is materialized as anpekko.stream.javadsl.SinkQueueWithCancel.static <T> Sink<T,SinkQueueWithCancel<T>> queue(int maxConcurrentPulls) Creates aSinkthat is materialized as anpekko.stream.javadsl.SinkQueueWithCancel.static <In> Sink<In,CompletionStage<In>> ASinkthat will invoke the given function for every received element, giving it its previous output (from the second element) and the element as input.<M> MrunWith(Graph<SourceShape<In>, M> source, ClassicActorSystemProvider systemProvider) Connect thisSinkto aSourceand run it.<M> MrunWith(Graph<SourceShape<In>, M> source, Materializer materializer) Connect thisSinkto aSourceand run it.static <In> Sink<In,CompletionStage<List<In>>> seq()ASinkthat keeps on collecting incoming elements until upstream terminates.shape()The shape of a graph is all that is externally visible: its inlets and outlets.source()ASinkthat materializes thisSinkitself as aSource.static <In> Sink<In,CompletionStage<List<In>>> takeLast(int n) ASinkthat materializes into aCompletionStageofListcontaining the lastncollected elements.toString()org.apache.pekko.stream.impl.LinearTraversalBuilderINTERNAL API.withAttributes(Attributes attr) Replace the attributes of thisSinkwith the given ones.
-
Constructor Details
-
Sink
-
-
Method Details
-
fold
ASinkthat will invoke the given function for every received element, giving it its previous output (or the givenzerovalue) and the element as input. The returnedCompletionStagewill be completed with value of the final function evaluation when the input stream ends, or completed withFailureif there is a failure is signaled in the stream. -
foldWhile
public static <U,In> Sink<In,CompletionStage<U>> foldWhile(U zero, Predicate<U> p, Function2<U, In, U> f) ASinkthat will invoke the given function for every received element, giving it its previous output (or the givenzerovalue) and the element as input. The returnedCompletionStagewill be completed with value of the final function evaluation when the input stream ends, predicatepreturns false, or completed withFailureif there is a failure is signaled in the stream.- Since:
- 1.1.0
-
foldAsync
public static <U,In> Sink<In,CompletionStage<U>> foldAsync(U zero, Function2<U, In, CompletionStage<U>> f) ASinkthat will invoke the given asynchronous function for every received element, giving it its previous output (or the givenzerovalue) and the element as input. The returnedCompletionStagewill be completed with value of the final function evaluation when the input stream ends, or completed withFailureif there is a failure is signaled in the stream. -
forall
ASinkthat will test the given predicatepfor every received element and 1. completes and returnsCompletionStageoftrueif the predicate is true for all elements; 2. completes and returnsCompletionStageoftrueif the stream is empty (i.e. completes before signalling any elements); 3. completes and returnsCompletionStageoffalseif the predicate is false for any element.The materialized value
CompletionStagewill be completed with the valuetrueorfalsewhen the input stream ends, or completed withFailureif there is a failure signaled in the stream.Adheres to the
ActorAttributes.SupervisionStrategyattribute.'''Completes when''' upstream completes or the predicate
preturnsfalse'''Backpressures when''' the invocation of predicate
phas not yet completed'''Cancels when''' predicate
preturnsfalse- Since:
- 1.1.0
-
none
ASinkthat will test the given predicatepfor every received element and 1. completes and returnsCompletionStageoftrueif the predicate is false for all elements; 2. completes and returnsCompletionStageoftrueif the stream is empty (i.e. completes before signalling any elements); 3. completes and returnsCompletionStageoffalseif the predicate is true for any element.The materialized value
CompletionStagewill be completed with the valuetrueorfalsewhen the input stream ends, or completed withFailureif there is a failure signaled in the stream.Adheres to the
ActorAttributes.SupervisionStrategyattribute.'''Completes when''' upstream completes or the predicate
preturnstrue'''Backpressures when''' the invocation of predicate
phas not yet completed'''Cancels when''' predicate
preturnstrue- Since:
- 1.2.0
-
exists
ASinkthat will test the given predicatepfor every received element and 1. completes and returnsCompletionStageoftrueif the predicate is true for any element; 2. completes and returnsCompletionStageoffalseif the stream is empty (i.e. completes before signalling any elements); 3. completes and returnsCompletionStageoffalseif the predicate is false for all elements.The materialized value
CompletionStagewill be completed with the valuetrueorfalsewhen the input stream ends, or completed withFailureif there is a failure signaled in the stream.Adheres to the
ActorAttributes.SupervisionStrategyattribute.'''Completes when''' upstream completes or the predicate
preturnstrue'''Backpressures when''' the invocation of predicate
phas not yet completed'''Cancels when''' predicate
preturnstrue- Since:
- 1.1.0
-
collect
Creates a sink which materializes into aCompletionStagewhich will be completed with a result of the JavaCollectortransformation and reduction operations. This allows usage of Java streams transformations for reactive streams. TheCollectorwill trigger demand downstream. Elements emitted through the stream will be accumulated into a mutable result container, optionally transformed into a final representation after all input elements have been processed. TheCollectorcan also do reduction at the end. Reduction processing is performed sequentially. -
reduce
ASinkthat will invoke the given function for every received element, giving it its previous output (from the second element) and the element as input. The returnedCompletionStagewill be completed with value of the final function evaluation when the input stream ends, or completed withFailureif there is a failure signaled in the stream.If the stream is empty (i.e. completes before signalling any elements), the reduce operator will fail its downstream with a
NoSuchElementException, which is semantically in-line with that Scala's standard library collections do in such situations. -
fromSubscriber
Helper to createSinkfromSubscriber. -
cancelled
ASinkthat immediately cancels its upstream after materialization. -
ignore
ASinkthat will consume the stream and discard the elements. -
never
ASinkthat will always backpressure never cancel and never consume any elements from the stream. -
asPublisher
ASinkthat materializes into aPublisher.If
fanoutistrue, the materializedPublisherwill support multipleSubscribers and the size of theinputBufferconfigured for this operator becomes the maximum number of elements that the fastestSubscribercan be ahead of the slowest one before slowing the processing down due to back pressure.If
fanoutisfalsethen the materializedPublisherwill only support a singleSubscriberand reject any additionalSubscribers. -
source
ASinkthat materializes thisSinkitself as aSource. The returnedSourceis a "live view" onto theSinkand only supports a singleSubscriber.Use
BroadcastHub#sinkif you need aSourcethat allows multiple subscribers.Note: even if the
Sourceis directly connected to theSink, there is still an asynchronous boundary between them; performance may be improved in the future.- Since:
- 1.3.0
-
foreach
ASinkthat will invoke the given procedure for each received element. The sink is materialized into aCompletionStagewhich will be completed withSuccesswhen reaching the normal end of the stream, or completed withFailureif there is a failure signaled in the stream. -
foreachAsync
public static <T> Sink<T,CompletionStage<Done>> foreachAsync(int parallelism, Function<T, CompletionStage<Void>> f) ASinkthat will invoke the given procedure asynchronously for each received element. The sink is materialized into aCompletionStagewhich will be completed withSuccesswhen reaching the normal end of the stream, or completed withFailureif there is a failure signaled in the stream. -
onComplete
ASinkthat when the flow is completed, either through a failure or normal completion, apply the provided function withSuccessorFailure. -
head
ASinkthat materializes into aCompletionStageof the first value received. If the stream completes before signaling at least a single element, the CompletionStage will be failed with aNoSuchElementException. If the stream signals an error before signaling at least a single element, the CompletionStage will be failed with the streams exception.See also
<In>headOption(). -
headOption
ASinkthat materializes into aCompletionStageof the optional first value received. If the stream completes before signaling at least a single element, the value of the CompletionStage will be an emptyOptional. If the stream signals an error errors before signaling at least a single element, the CompletionStage will be failed with the streams exception.See also
<In>head(). -
last
ASinkthat materializes into aCompletionStageof the last value received. If the stream completes before signaling at least a single element, the CompletionStage will be failed with aNoSuchElementException. If the stream signals an error errors before signaling at least a single element, the CompletionStage will be failed with the streams exception.See also
<In>lastOption(),<In>takeLast(int). -
lastOption
ASinkthat materializes into aCompletionStageof the optional last value received. If the stream completes before signaling at least a single element, the value of the CompletionStage will be an emptyOptional. If the stream signals an error errors before signaling at least a single element, the CompletionStage will be failed with the streams exception.See also
<In>head(),<In>takeLast(int). -
takeLast
ASinkthat materializes into aCompletionStageofListcontaining the lastncollected elements.If the stream completes before signaling at least n elements, the
CompletionStagewill complete with all elements seen so far. If the stream never completes theCompletionStagewill never complete. If there is a failure signaled in the stream theCompletionStagewill be completed with failure. -
seq
ASinkthat keeps on collecting incoming elements until upstream terminates. As upstream may be unbounded,Flow[T].takeor the stricterFlow[T].limit(and their variants) may be used to ensure boundedness. Materializes into aCompletionStageofSeq[T]containing all the collected elements.Listis limited toInteger.MAX_VALUEelements, this Sink will cancel the stream after having received that many elements.See also
Flow.limit,Flow.limitWeighted,Flow.take,Flow.takeWithin,Flow.takeWhile -
count
ASinkthat counts all incoming elements until upstream terminates.Since upstream may be unbounded, consider using
Flow[T].takeor the stricterFlow[T].limit(and their variants) to ensure boundedness. The sink materializes into aCompletionStageofLongcontaining the total count of elements that passed through.'''Completes when''' upstream completes
'''Backpressures when''' never (counting is a lightweight operation)
'''Cancels when''' never
- Returns:
- a
Sinkthat materializes to aCompletionStage[Long]with the element count - Since:
- 2.0.0
See also
Flow.limit,Flow.limitWeighted,Flow.take,Flow.takeWithin,Flow.takeWhile
-
actorRef
Sends the elements of the stream to the givenActorRef. If the target actor terminates the stream will be canceled. When the stream is completed successfully the givenonCompleteMessagewill be sent to the destination actor. When the stream is completed with failure apekko.actor.Status.Failuremessage will be sent to the destination actor.It will request at most
maxInputBufferSizenumber of elements from upstream, but there is no back-pressure signal from the destination actor, i.e. if the actor is not consuming the messages fast enough the mailbox of the actor will grow. For potentially slow consumer actors it is recommended to use a bounded mailbox with zeromailbox-push-timeout-timeor use a rate limiting operator in front of thisSink. -
actorRefWithBackpressure
public static <In> Sink<In,NotUsed> actorRefWithBackpressure(ActorRef ref, Object onInitMessage, Object ackMessage, Object onCompleteMessage, Function<Throwable, Object> onFailureMessage) Sends the elements of the stream to the givenActorRefthat sends back back-pressure signal. First element is alwaysonInitMessage, then stream is waiting for acknowledgement messageackMessagefrom the given actor which means that it is ready to process elements. It also requiresackMessagemessage after each stream element to make backpressure work.If the target actor terminates the stream will be canceled. When the stream is completed successfully the given
onCompleteMessagewill be sent to the destination actor. When the stream is completed with failure - result ofonFailureMessage(throwable)message will be sent to the destination actor. -
actorRefWithBackpressure
public static <In> Sink<In,NotUsed> actorRefWithBackpressure(ActorRef ref, Object onInitMessage, Object onCompleteMessage, Function<Throwable, Object> onFailureMessage) Sends the elements of the stream to the givenActorRefthat sends back back-pressure signal. First element is alwaysonInitMessage, then stream is waiting for acknowledgement message from the given actor which means that it is ready to process elements. It also requires an ack message after each stream element to make backpressure work. This variant will consider any message as ack message.If the target actor terminates the stream will be canceled. When the stream is completed successfully the given
onCompleteMessagewill be sent to the destination actor. When the stream is completed with failure - result ofonFailureMessage(throwable)message will be sent to the destination actor. -
fromGraph
A graph with the shape of a sink logically is a sink, this method makes it so also in type. -
fromMaterializer
public static <T,M> Sink<T,CompletionStage<M>> fromMaterializer(Function2<Materializer, Attributes, Sink<T, M>> factory) -
combine
public static <T,U> Sink<T,NotUsed> combine(Sink<U, ?> output1, Sink<U, ?> output2, List<Sink<U, ?>> rest, Function<Integer, Graph<UniformFanOutShape<T, U>, NotUsed>> fanOutStrategy) Combine several sinks with fan-out strategy likeBroadcastorBalanceand returnsSink. -
combineMat
public static <T,U, Sink<T,M1, M2, M> M> combineMat(Sink<U, M1> first, Sink<U, M2> second, Function<Integer, Graph<UniformFanOutShape<T, U>, NotUsed>> fanOutStrategy, Function2<M1, M2, M> matF) Combine two sinks with fan-out strategy likeBroadcastorBalanceand returnsSinkwith 2 outlets.- Since:
- 1.1.0
-
combine
public static <T,U, Sink<T,M> List<M>> combine(List<? extends Graph<SinkShape<U>, M>> sinks, Function<Integer, Graph<UniformFanOutShape<T, U>, NotUsed>> fanOutStrategy) Combine several sinks with fan-out strategy likeBroadcastorBalanceand returnsSink. The fanoutGraph's outlets size must match the provides sinks'.- Since:
- 1.1.0
-
queue
Creates aSinkthat is materialized as anpekko.stream.javadsl.SinkQueueWithCancel.pekko.stream.javadsl.SinkQueueWithCancel.pullmethod is pulling element from the stream and returnsCompletionStage[Option[T}.CompletionStagecompletes when element is available.Before calling pull method second time you need to ensure that number of pending pulls is less then
maxConcurrentPullsor wait until some of the previous Futures completes. Pull returns Failed future with ''IllegalStateException'' if there will be more thenmaxConcurrentPullsnumber of pending pulls.Sinkwill request at most number of elements equal to size ofinputBufferfrom upstream and then stop back pressure. You can configure size of input buffer by usingSink.withAttributesmethod.For stream completion you need to pull all elements from
pekko.stream.javadsl.SinkQueueWithCancelincluding last None as completion marker- See Also:
-
pekko.stream.javadsl.SinkQueueWithCancel
-
queue
Creates aSinkthat is materialized as anpekko.stream.javadsl.SinkQueueWithCancel.pekko.stream.javadsl.SinkQueueWithCancel.pullmethod is pulling element from the stream and returnsCompletionStage[Option[T}.CompletionStagecompletes when element is available.Before calling pull method second time you need to wait until previous CompletionStage completes. Pull returns Failed future with ''IllegalStateException'' if previous future has not yet completed.
Sinkwill request at most number of elements equal to size ofinputBufferfrom upstream and then stop back pressure. You can configure size of input buffer by usingSink.withAttributesmethod.For stream completion you need to pull all elements from
pekko.stream.javadsl.SinkQueueWithCancelincluding last None as completion marker- See Also:
-
pekko.stream.javadsl.SinkQueueWithCancel
-
completionStageSink
public static <T,M> Sink<T,CompletionStage<M>> completionStageSink(CompletionStage<Sink<T, M>> future) Turn aFuture[Sink]into a Sink that will consume the values of the source when the future completes successfully. If theFutureis completed with a failure the stream is failed.The materialized future value is completed with the materialized value of the future sink or failed with a
NeverMaterializedExceptionif upstream fails or downstream cancels before the future has completed. -
lazySink
Defers invoking thecreatefunction to create a sink until there is a first element passed from upstream.The materialized future value is completed with the materialized value of the created sink when that has successfully been materialized.
If the
createfunction throws or returns or the stream fails to materialize, in this case the materialized future value is failed with apekko.stream.NeverMaterializedException. -
lazyCompletionStageSink
public static <T,M> Sink<T,CompletionStage<M>> lazyCompletionStageSink(Creator<CompletionStage<Sink<T, M>>> create) Defers invoking thecreatefunction to create a future sink until there is a first element passed from upstream.The materialized future value is completed with the materialized value of the created sink when that has successfully been materialized.
If the
createfunction throws or returns a future that is failed, or the stream fails to materialize, in this case the materialized future value is failed with apekko.stream.NeverMaterializedException. -
shape
Description copied from interface:GraphThe shape of a graph is all that is externally visible: its inlets and outlets. -
traversalBuilder
public org.apache.pekko.stream.impl.LinearTraversalBuilder traversalBuilder()Description copied from interface:GraphINTERNAL API.Every materializable element must be backed by a stream layout module
- Specified by:
traversalBuilderin interfaceGraph<In,Mat>
-
toString
-
asScala
Converts this Sink to its Scala DSL counterpart. -
runWith
Connect thisSinkto aSourceand run it.Note that the
ActorSystemcan be used as thesystemProviderparameter. -
runWith
Connect thisSinkto aSourceand run it. -
contramap
Transform this Sink by applying a function to each *incoming* upstream element before it is passed to theSink'''Backpressures when''' original
Sinkbackpressures'''Cancels when''' original
Sinkbackpressures- Since:
- 1.1.0
-
mapMaterializedValue
Transform only the materialized value of this Sink, leaving all other properties as they were. -
preMaterialize
Materializes this Sink, immediately returning (1) its materialized value, and (2) a new Sink that can be consume elements 'into' the pre-materialized one.Useful for when you need a materialized value of a Sink when handing it out to someone to materialize it for you.
Note that the
ActorSystemcan be used as thesystemProviderparameter. -
preMaterialize
Materializes this Sink, immediately returning (1) its materialized value, and (2) a new Sink that can be consume elements 'into' the pre-materialized one.Useful for when you need a materialized value of a Sink when handing it out to someone to materialize it for you.
Prefer the method taking an ActorSystem unless you have special requirements.
-
withAttributes
Replace the attributes of thisSinkwith the given ones. If this Sink is a composite of multiple graphs, new attributes on the composite will be less specific than attributes set directly on the individual graphs of the composite.- Specified by:
withAttributesin interfaceGraph<In,Mat>
-
addAttributes
Add the given attributes to thisSink. If the specific attribute was already present on this graph this means the added attribute will be more specific than the existing one. If this Sink is a composite of multiple graphs, new attributes on the composite will be less specific than attributes set directly on the individual graphs of the composite.- Specified by:
addAttributesin interfaceGraph<In,Mat>
-
named
Add anameattribute to this Sink. -
async
Put an asynchronous boundary around thisSink -
async
Put an asynchronous boundary around thisSink -
async
Put an asynchronous boundary around thisSink -
getAttributes
- Specified by:
getAttributesin interfaceGraph<In,Mat>
-