Interface StreamMessage<T>
- Type Parameters:
T- the type of element signaled
- All Superinterfaces:
org.reactivestreams.Publisher<T>
- All Known Subinterfaces:
ByteStreamMessage,HttpMessage,HttpRequest,HttpRequestWriter,HttpResponse,HttpResponseWriter,StreamWriter<T>,WebSocket,WebSocketWriter
- All Known Implementing Classes:
DefaultStreamMessage,DeferredStreamMessage,FilteredHttpRequest,FilteredHttpResponse,FilteredStreamMessage,PublisherBasedStreamMessage,StreamMessageWrapper
Publisher, which allows
only one Subscriber. Unlike a usual Publisher, a StreamMessage can stream itself
only once. It has the following additional operations on top of what the Reactive Streams API provides:
When is a StreamMessage fully consumed?
A StreamMessage is complete (or 'fully consumed') when:
- the
Subscriberconsumes all elements andSubscriber.onComplete()is invoked, - an error occurred and
Subscriber.onError(Throwable)is invoked, - the
Subscriptionhas been cancelled or abort()has been requested.
When fully consumed, the CompletableFuture returned by whenComplete()
will complete, which you may find useful because Subscriber does not notify you when a stream is
cancelled.
Publication and Consumption of pooled HttpData objects
StreamMessage will discard the publication request of a pooled HttpData silently and
release it automatically when the publication is attempted after the stream is closed.
For pooled HttpData, StreamMessage will convert them into its unpooled version that
never leak, so that the Subscriber does not need to worry about leaks.
If a Subscriber does not want a StreamMessage to make a copy of a pooled HttpData,
specify SubscriptionOption.WITH_POOLED_OBJECTS when you subscribe. Note that the Subscriber
is responsible for releasing the objects given with Subscriber.onNext(Object).
Subscriber.onError(Throwable) is invoked when any exception is raised except the
CancelledSubscriptionException which is caused by Subscription.cancel(). If you want your
Subscriber get notified by Subscriber.onError(Throwable) when Subscription.cancel()
is called, specify SubscriptionOption.NOTIFY_CANCELLATION when you subscribe.
-
Method Summary
Modifier and TypeMethodDescriptionvoidabort()Closes this stream withAbortedStreamExceptionand prevents further subscription.voidCloses this stream with the specifiedThrowableand prevents further subscription.static <T> StreamMessage<T>Returns an abortedStreamMessagethat terminates with the specifiedThrowableviaSubscriber.onError(Throwable)immediately after being subscribed to.builder(InputStream inputStream) Returns a newInputStreamStreamMessageBuilderwith the specifiedInputStream.static PathStreamMessageBuilderReturns a newPathStreamMessageBuilderwith the specifiedPath.default CompletableFuture<List<T>>collect()Collects the elements published by thisStreamMessage.default CompletableFuture<List<T>>collect(SubscriptionOption... options) Collects the elements published by thisStreamMessagewith the specifiedSubscriptionOptions.default CompletableFuture<List<T>>collect(EventExecutor executor, SubscriptionOption... options) Collects the elements published by thisStreamMessagewith the specifiedEventExecutorandSubscriptionOptions.static <T> StreamMessage<T>Returns a concatenatedStreamMessagewhich relays items of the specifiedPublishers in order, non-overlappingly, one after the other finishes.static <T> StreamMessage<T>concat(org.reactivestreams.Publisher<? extends org.reactivestreams.Publisher<? extends T>> publishers) Returns a concatenatedStreamMessagewhich relays items of the specifiedPublisherofPublishers in order, non-overlappingly, one after the other finishes.static <T> StreamMessage<T>concat(org.reactivestreams.Publisher<? extends T>... publishers) Returns a concatenatedStreamMessagewhich relays items of the specified array ofPublishers in order, non-overlappingly, one after the other finishes.default <U> StreamMessage<U>decode(StreamDecoder<T, U> decoder) Creates a decodedStreamMessagewhich is decoded from a stream ofTtype objects using the specifiedStreamDecoder.default <U> StreamMessage<U>decode(StreamDecoder<T, U> decoder, ByteBufAllocator alloc) Creates a decodedStreamMessagewhich is decoded from a stream ofTtype objects using the specifiedStreamDecoderandByteBufAllocator.default EventExecutorReturns the defaultEventExecutorwhich will be used when a user subscribes usingsubscribe(Subscriber),subscribe(Subscriber, SubscriptionOption...).longdemand()Returns the current demand of this stream.default StreamMessage<T>Dynamically emits the last value depending on whether thisStreamMessagecompletes successfully or exceptionally.default StreamMessage<T>Filters values emitted by thisStreamMessage.static ByteStreamMessagefromOutputStream(Consumer<? super OutputStream> outputStreamConsumer) static ByteStreamMessagefromOutputStream(Consumer<? super OutputStream> outputStreamConsumer, Executor blockingTaskExecutor) default booleanReturnstrueif this stream is complete, either successfully or exceptionally, including cancellation and abortion.booleanisEmpty()Returnstrueif this stream has been closed and did not publish any elements.booleanisOpen()Returnstrueif this stream is not closed yet.default <U> StreamMessage<U>Transforms values emitted by thisStreamMessageby applying the specifiedFunction.default <U> StreamMessage<U>mapAsync(Function<? super T, ? extends CompletableFuture<? extends U>> function) Transforms values emitted by thisStreamMessageby applying the specified asynchronousFunctionand emitting the value the future completes with.default StreamMessage<T>Transforms an error emitted by thisStreamMessageby applying the specifiedFunction.default <U> StreamMessage<U>mapParallel(Function<? super T, ? extends CompletableFuture<? extends U>> function) Transforms values emitted by thisStreamMessageby applying the specified asynchronousFunctionand emitting the value the future completes with.default <U> StreamMessage<U>mapParallel(Function<? super T, ? extends CompletableFuture<? extends U>> function, int maxConcurrency) Transforms values emitted by thisStreamMessageby applying the specified asynchronousFunctionand emitting the value the future completes with.static <T> StreamMessage<T>of()Creates a newStreamMessagethat will publish no objects, just a close event.static ByteStreamMessageCreates a newStreamMessagethat streams the specifiedFile.static ByteStreamMessageof(InputStream inputStream) Creates a newStreamMessagethat streams bytes from the specifiedInputStream.static ByteStreamMessageCreates a newStreamMessagethat streams the specifiedPath.static ByteStreamMessageDeprecated.static ByteStreamMessageof(Path path, ByteBufAllocator alloc, int bufferSize) Deprecated.static ByteStreamMessageof(Path path, @Nullable ExecutorService executor, ByteBufAllocator alloc, int bufferSize) static <T> StreamMessage<T>of(CompletableFuture<? extends org.reactivestreams.Publisher<? extends T>> future) Creates a newStreamMessagethat delegates to theStreamMessageproduced by the specifiedCompletableFuture.static <T> StreamMessage<T>of(CompletionStage<? extends StreamMessage<? extends T>> stage, EventExecutor subscriberExecutor) Creates a newStreamMessagethat delegates to theStreamMessageproduced by the specifiedCompletionStage.static <T> StreamMessage<T>of(CompletionStage<? extends org.reactivestreams.Publisher<? extends T>> stage) Creates a newStreamMessagethat delegates to theStreamMessageproduced by the specifiedCompletionStage.static <T> StreamMessage<T>of(org.reactivestreams.Publisher<? extends T> publisher) Creates a newStreamMessagefrom the specifiedPublisher.static <T> StreamMessage<T>of(T obj) Creates a newStreamMessagethat will publish the singleobj.static <T> StreamMessage<T>of(T... objs) Creates a newStreamMessagethat will publish the givenobjs.static <T> StreamMessage<T>of(T obj1, T obj2) static <T> StreamMessage<T>of(T obj1, T obj2, T obj3) default StreamMessage<T>Peeks values emitted by thisStreamMessageand applies the specifiedConsumer.default <U extends T>
StreamMessage<T>Peeks values emitted by thisStreamMessageand applies the specifiedConsumer.default StreamMessage<T>Peeks an error emitted by thisStreamMessageand applies the specifiedConsumer.default <E extends Throwable>
StreamMessage<T>recoverAndResume(Class<E> causeClass, Function<? super E, ? extends StreamMessage<T>> function) Recovers a failedStreamMessageand resumes by subscribing to a returned fallbackStreamMessagewhen the thrownThrowableis the same type or a subtype of the specifiedcauseClass.default StreamMessage<T>recoverAndResume(Function<? super Throwable, ? extends StreamMessage<T>> function) Recovers a failedStreamMessageand resumes by subscribing to a returned fallbackStreamMessagewhen any error occurs.static <T> StreamWriter<T>Creates a newStreamWriterthat publishes the objects written viaStreamWriter.write(Object).default CompletableFuture<Void>Drains and discards all objects in thisStreamMessage.default CompletableFuture<Void>subscribe(EventExecutor executor) Drains and discards all objects in thisStreamMessage.default voidRequests to start streaming data to the specifiedSubscriber.default voidsubscribe(org.reactivestreams.Subscriber<? super T> subscriber, SubscriptionOption... options) Requests to start streaming data to the specifiedSubscriber.default voidsubscribe(org.reactivestreams.Subscriber<? super T> subscriber, EventExecutor executor) Requests to start streaming data to the specifiedSubscriber.voidsubscribe(org.reactivestreams.Subscriber<? super T> subscriber, EventExecutor executor, SubscriptionOption... options) Requests to start streaming data to the specifiedSubscriber.default StreamMessage<T>subscribeOn(EventExecutor eventExecutor) Callssubscribe(Subscriber, EventExecutor)to the upstreamStreamMessageusing the specifiedEventExecutorand relays the stream transparently downstream.default StreamMessageDuplicator<T>Returns a newStreamMessageDuplicatorthat duplicates thisStreamMessageinto one or moreStreamMessages, which publish the same elements.default StreamMessageDuplicator<T>toDuplicator(EventExecutor executor) Returns a newStreamMessageDuplicatorthat duplicates thisStreamMessageinto one or moreStreamMessages, which publish the same elements.default InputStreamtoInputStream(Function<? super T, ? extends HttpData> httpDataConverter) Adapts thisStreamMessagetoInputStream.default InputStreamtoInputStream(Function<? super T, ? extends HttpData> httpDataConverter, EventExecutor executor) Adapts thisStreamMessagetoInputStream.Returns aCompletableFuturethat completes when this stream is complete, either successfully or exceptionally, including cancellation and abortion.default CompletableFuture<Void>
-
Method Details
-
of
Creates a newStreamMessagethat will publish no objects, just a close event. -
of
Creates a newStreamMessagethat will publish the singleobj. -
of
-
of
-
of
Creates a newStreamMessagethat will publish the givenobjs. -
of
Creates a newStreamMessagefrom the specifiedPublisher. -
of
@UnstableApi static <T> StreamMessage<T> of(CompletableFuture<? extends org.reactivestreams.Publisher<? extends T>> future) Creates a newStreamMessagethat delegates to theStreamMessageproduced by the specifiedCompletableFuture. If the specifiedCompletableFuturefails, the returnedStreamMessagewill be closed with the same cause as well.- Parameters:
future- theCompletableFuturewhich will produce the actualStreamMessage
-
of
@UnstableApi static <T> StreamMessage<T> of(CompletionStage<? extends org.reactivestreams.Publisher<? extends T>> stage) Creates a newStreamMessagethat delegates to theStreamMessageproduced by the specifiedCompletionStage. If the specifiedCompletionStagefails, the returnedStreamMessagewill be closed with the same cause as well.- Parameters:
stage- theCompletionStagewhich will produce the actualStreamMessage
-
of
static <T> StreamMessage<T> of(CompletionStage<? extends StreamMessage<? extends T>> stage, EventExecutor subscriberExecutor) Creates a newStreamMessagethat delegates to theStreamMessageproduced by the specifiedCompletionStage. If the specifiedCompletionStagefails, the returnedStreamMessagewill be closed with the same cause as well.- Parameters:
stage- theCompletionStagewhich will produce the actualStreamMessagesubscriberExecutor- theEventExecutorwhich will be used when a user subscribes the returnedStreamMessageusingsubscribe(Subscriber)orsubscribe(Subscriber, SubscriptionOption...).
-
of
Creates a newStreamMessagethat streams the specifiedFile. The default buffer size(8192) is used to create a buffer used to read data from theFile. Therefore, the returnedStreamMessagewill emitHttpDatas chunked to size less than or equal to 8192. -
of
Creates a newStreamMessagethat streams the specifiedPath. The default buffer size(8192) is used to create a buffer used to read data from thePath. Therefore, the returnedStreamMessagewill emitHttpDatas chunked to size less than or equal to 8192. -
builder
Returns a newPathStreamMessageBuilderwith the specifiedPath. -
of
Deprecated.Creates a newStreamMessagethat streams the specifiedPath. The specifiedbufferSizeis used to create a buffer used to read data from thePath. Therefore, the returnedStreamMessagewill emitHttpDatas chunked to size less than or equal tobufferSize.- Parameters:
path- the path of the filebufferSize- the maximum allowed size of theHttpDatabuffers
-
of
Deprecated.Creates a newStreamMessagethat streams the specifiedPath. The specifiedbufferSizeis used to create a buffer used to read data from thePath. Therefore, the returnedStreamMessagewill emitHttpDatas chunked to size less than or equal tobufferSize.- Parameters:
path- the path of the filealloc- theByteBufAllocatorwhich will allocate the content bufferbufferSize- the maximum allowed size of theHttpDatabuffers
-
of
@Deprecated static ByteStreamMessage of(Path path, @Nullable @Nullable ExecutorService executor, ByteBufAllocator alloc, int bufferSize) Deprecated.Creates a newStreamMessagethat streams the specifiedPath. The specifiedbufferSizeis used to create a buffer used to read data from thePath. Therefore, the returnedStreamMessagewill emitHttpDatas chunked to size less than or equal tobufferSize.- Parameters:
path- the path of the fileexecutor- theExecutorServicewhich performs blocking IO readalloc- theByteBufAllocatorwhich will allocate the content bufferbufferSize- the maximum allowed size of theHttpDatabuffers
-
of
Creates a newStreamMessagethat streams bytes from the specifiedInputStream. The default buffer size(8192) is used to create a buffer that is used to read data from theInputStream. Therefore, the returnedStreamMessagewill emitHttpDatas chunked to size less than or equal to 8192. -
builder
Returns a newInputStreamStreamMessageBuilderwith the specifiedInputStream. -
fromOutputStream
Creates a newByteStreamMessagethat publishesHttpDatas from the specified outputStreamConsumer.For example:
ByteStreamMessage byteStreamMessage = StreamMessage.fromOutputStream(os -> { try { for (int i = 0; i < 5; i++) { os.write(i); } os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } }); byte[] result = byteStreamMessage.collectBytes().join(); assert Arrays.equals(result, new byte[] { 0, 1, 2, 3, 4 });Please note that the try-with-resources statement is not used to call
os.close()automatically. It's because when an exception is raised in theConsumer, theOutputStreamis closed by theStreamMessageand the exception is propagated to theSubscriberautomatically. -
fromOutputStream
static ByteStreamMessage fromOutputStream(Consumer<? super OutputStream> outputStreamConsumer, Executor blockingTaskExecutor) Creates a newByteStreamMessagethat publishesHttpDatas from the specified outputStreamConsumer.For example:
ByteStreamMessage byteStreamMessage = StreamMessage.fromOutputStream(os -> { try { for (int i = 0; i < 5; i++) { os.write(i); } os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } }); byte[] result = byteStreamMessage.collectBytes().join(); assert Arrays.equals(result, new byte[] { 0, 1, 2, 3, 4 });Please note that the try-with-resources statement is not used to call
os.close()automatically. It's because when an exception is raised in theConsumer, theOutputStreamis closed by theStreamMessageand the exception is propagated to theSubscriberautomatically.- Parameters:
blockingTaskExecutor- the blocking task executor to executeOutputStream.write(int)
-
concat
@SafeVarargs static <T> StreamMessage<T> concat(org.reactivestreams.Publisher<? extends T>... publishers) Returns a concatenatedStreamMessagewhich relays items of the specified array ofPublishers in order, non-overlappingly, one after the other finishes. -
concat
static <T> StreamMessage<T> concat(Iterable<? extends org.reactivestreams.Publisher<? extends T>> publishers) Returns a concatenatedStreamMessagewhich relays items of the specifiedPublishers in order, non-overlappingly, one after the other finishes. -
concat
static <T> StreamMessage<T> concat(org.reactivestreams.Publisher<? extends org.reactivestreams.Publisher<? extends T>> publishers) Returns a concatenatedStreamMessagewhich relays items of the specifiedPublisherofPublishers in order, non-overlappingly, one after the other finishes. -
aborted
Returns an abortedStreamMessagethat terminates with the specifiedThrowableviaSubscriber.onError(Throwable)immediately after being subscribed to. -
streaming
Creates a newStreamWriterthat publishes the objects written viaStreamWriter.write(Object). -
isOpen
boolean isOpen()Returnstrueif this stream is not closed yet. Note that a stream may not be complete even if it's closed; a stream is complete when it's fully consumed by aSubscriber. -
isEmpty
boolean isEmpty()Returnstrueif this stream has been closed and did not publish any elements. Note that this method will not returntruewhen the stream is open even if it has not published anything so far, because it may publish something later. -
demand
long demand()Returns the current demand of this stream. -
isComplete
default boolean isComplete()Returnstrueif this stream is complete, either successfully or exceptionally, including cancellation and abortion.A
StreamMessageis complete (or 'fully consumed') when:- the
Subscriberconsumes all elements andSubscriber.onComplete()is invoked, - an error occurred and
Subscriber.onError(Throwable)is invoked, - the
Subscriptionhas been cancelled or abort()has been requested.
- the
-
whenComplete
CompletableFuture<Void> whenComplete()Returns aCompletableFuturethat completes when this stream is complete, either successfully or exceptionally, including cancellation and abortion.A
StreamMessageis complete (or 'fully consumed') when:- the
Subscriberconsumes all elements andSubscriber.onComplete()is invoked, - an error occurred and
Subscriber.onError(Throwable)is invoked, - the
Subscriptionhas been cancelled or abort()has been requested.
- the
-
subscribe
Drains and discards all objects in thisStreamMessage.For example:
StreamMessage<Integer> source = StreamMessage.of(1, 2, 3); List<Integer> collected = new ArrayList<>(); CompletableFuture<Void> future = source.peek(collected::add).subscribe(); future.join(); assert collected.equals(List.of(1, 2, 3)); assert future.isDone(); -
subscribe
Drains and discards all objects in thisStreamMessage.For example:
StreamMessage<Integer> source = StreamMessage.of(1, 2, 3); List<Integer> collected = new ArrayList<>(); CompletableFuture<Void> future = source.peek(collected::add).subscribe(); future.join(); assert collected.equals(List.of(1, 2, 3)); assert future.isDone();- Parameters:
executor- the executor to subscribe
-
subscribe
Requests to start streaming data to the specifiedSubscriber. If there is a problem subscribing,Subscriber.onError(Throwable)will be invoked with one of the following exceptions:IllegalStateExceptionif otherSubscribersubscribed to this stream already.AbortedStreamExceptionif this stream has been aborted.CancelledSubscriptionExceptionif this stream has been cancelled andSubscriptionOption.NOTIFY_CANCELLATIONis specified when subscribed.- Other exceptions that occurred due to an error while retrieving the elements.
- Specified by:
subscribein interfaceorg.reactivestreams.Publisher<T>
-
subscribe
default void subscribe(org.reactivestreams.Subscriber<? super T> subscriber, SubscriptionOption... options) Requests to start streaming data to the specifiedSubscriber. If there is a problem subscribing,Subscriber.onError(Throwable)will be invoked with one of the following exceptions:IllegalStateExceptionif otherSubscribersubscribed to this stream already.AbortedStreamExceptionif this stream has been aborted.CancelledSubscriptionExceptionif this stream has been cancelled andSubscriptionOption.NOTIFY_CANCELLATIONis specified when subscribed.- Other exceptions that occurred due to an error while retrieving the elements.
- Parameters:
options-SubscriptionOptions to subscribe with
-
subscribe
default void subscribe(org.reactivestreams.Subscriber<? super T> subscriber, EventExecutor executor) Requests to start streaming data to the specifiedSubscriber. If there is a problem subscribing,Subscriber.onError(Throwable)will be invoked with one of the following exceptions:IllegalStateExceptionif otherSubscribersubscribed to this stream already.AbortedStreamExceptionif this stream has been aborted.CancelledSubscriptionExceptionif this stream has been cancelled andSubscriptionOption.NOTIFY_CANCELLATIONis specified when subscribed.- Other exceptions that occurred due to an error while retrieving the elements.
- Parameters:
executor- the executor to subscribe
-
subscribe
void subscribe(org.reactivestreams.Subscriber<? super T> subscriber, EventExecutor executor, SubscriptionOption... options) Requests to start streaming data to the specifiedSubscriber. If there is a problem subscribing,Subscriber.onError(Throwable)will be invoked with one of the following exceptions:IllegalStateExceptionif otherSubscribersubscribed to this stream already.AbortedStreamExceptionif this stream has been aborted.CancelledSubscriptionExceptionif this stream has been cancelled andSubscriptionOption.NOTIFY_CANCELLATIONis specified when subscribed.- Other exceptions that occurred due to an error while retrieving the elements.
- Parameters:
executor- the executor to subscribeoptions-SubscriptionOptions to subscribe with
-
toDuplicator
Returns a newStreamMessageDuplicatorthat duplicates thisStreamMessageinto one or moreStreamMessages, which publish the same elements. Note that you cannot subscribe to thisStreamMessageanymore after you call this method. To subscribe, callStreamMessageDuplicator.duplicate()from the returnedStreamMessageDuplicator. -
toDuplicator
Returns a newStreamMessageDuplicatorthat duplicates thisStreamMessageinto one or moreStreamMessages, which publish the same elements. Note that you cannot subscribe to thisStreamMessageanymore after you call this method. To subscribe, callStreamMessageDuplicator.duplicate()from the returnedStreamMessageDuplicator.- Parameters:
executor- the executor to duplicate
-
defaultSubscriberExecutor
Returns the defaultEventExecutorwhich will be used when a user subscribes usingsubscribe(Subscriber),subscribe(Subscriber, SubscriptionOption...).Please note that if this method is called multiple times, the returned
EventExecutors can be different depending on thisStreamMessageimplementation. -
abort
void abort()Closes this stream withAbortedStreamExceptionand prevents further subscription. ASubscriberthat attempts to subscribe to an aborted stream will be notified with anAbortedStreamExceptionviaSubscriber.onError(Throwable). Calling this method on a closed or aborted stream has no effect. -
abort
-
decode
Creates a decodedStreamMessagewhich is decoded from a stream ofTtype objects using the specifiedStreamDecoder. -
decode
@UnstableApi default <U> StreamMessage<U> decode(StreamDecoder<T, U> decoder, ByteBufAllocator alloc) Creates a decodedStreamMessagewhich is decoded from a stream ofTtype objects using the specifiedStreamDecoderandByteBufAllocator. -
collect
Collects the elements published by thisStreamMessage. The returnedCompletableFuturewill be notified when the elements are fully consumed.Note that if this
StreamMessagewas subscribed by otherSubscriberalready, the returnedCompletableFuturewill be completed with anIllegalStateException.StreamMessage<Integer> stream = StreamMessage.of(1, 2, 3); CompletableFuture<List<Integer>> collected = stream.collect(); assert collected.join().equals(List.of(1, 2, 3)); -
collect
Collects the elements published by thisStreamMessagewith the specifiedSubscriptionOptions. The returnedCompletableFuturewill be notified when the elements are fully consumed.Note that if this
StreamMessagewas subscribed by otherSubscriberalready, the returnedCompletableFuturewill be completed with anIllegalStateException. -
collect
Collects the elements published by thisStreamMessagewith the specifiedEventExecutorandSubscriptionOptions. The returnedCompletableFuturewill be notified when the elements are fully consumed.Note that if this
StreamMessagewas subscribed by otherSubscriberalready, the returnedCompletableFuturewill be completed with anIllegalStateException. -
filter
Filters values emitted by thisStreamMessage. If thePredicatetest succeeds, the value is emitted. If thePredicatetest fails, the value is ignored and a request of1is made to upstream.For example:
StreamMessage<Integer> source = StreamMessage.of(1, 2, 3, 4, 5); StreamMessage<Integer> even = source.filter(x -> x % 2 == 0); -
map
Transforms values emitted by thisStreamMessageby applying the specifiedFunction. As per Reactive Streams Specification 2.13, the specifiedFunctionshould not return anullvalue.For example:
StreamMessage<Integer> source = StreamMessage.of(1, 2, 3, 4, 5); StreamMessage<Boolean> isEven = source.map(x -> x % 2 == 0); -
mapAsync
default <U> StreamMessage<U> mapAsync(Function<? super T, ? extends CompletableFuture<? extends U>> function) Transforms values emitted by thisStreamMessageby applying the specified asynchronousFunctionand emitting the value the future completes with. TheStreamMessagepublishes items in order, non-overlappingly, one after the other finishes. As per Reactive Streams Specification 2.13, the specifiedFunctionshould not return anullvalue nor a future which completes with anullvalue.Example:
StreamMessage<Integer> streamMessage = StreamMessage.of(1, 2, 3, 4, 5); StreamMessage<Integer> transformed = streamMessage.mapAsync(x -> UnmodifiableFuture.completedFuture(x + 1)); -
mapParallel
@UnstableApi default <U> StreamMessage<U> mapParallel(Function<? super T, ? extends CompletableFuture<? extends U>> function) Transforms values emitted by thisStreamMessageby applying the specified asynchronousFunctionand emitting the value the future completes with. TheStreamMessagepublishes items eagerly in the order that the futures complete. It does not necessarily preserve the order of the original stream. As per Reactive Streams Specification 2.13, the specifiedFunctionshould not return anullvalue nor a future which completes with anullvalue.Example:
StreamMessage<Integer> streamMessage = StreamMessage.of(1, 2, 3, 4, 5); StreamMessage<Integer> transformed = streamMessage.mapParallel(x -> UnmodifiableFuture.completedFuture(x + 1)); -
mapParallel
@UnstableApi default <U> StreamMessage<U> mapParallel(Function<? super T, ? extends CompletableFuture<? extends U>> function, int maxConcurrency) Transforms values emitted by thisStreamMessageby applying the specified asynchronousFunctionand emitting the value the future completes with. TheStreamMessagepublishes items eagerly in the order that the futures complete. The number of pending futures will at most bemaxConcurrencyIt does not necessarily preserve the order of the original stream. As per Reactive Streams Specification 2.13, the specifiedFunctionshould not return anullvalue nor a future which completes with anullvalue.Example:
StreamMessage<Integer> streamMessage = StreamMessage.of(1, 2, 3, 4, 5); StreamMessage<Integer> transformed = streamMessage.mapParallel(x -> UnmodifiableFuture.completedFuture(x + 1), 20); -
mapError
Transforms an error emitted by thisStreamMessageby applying the specifiedFunction. As per Reactive Streams Specification 2.13, the specifiedFunctionshould not return anullvalue.For example:
StreamMessage<Void> streamMessage = StreamMessage .aborted(new IllegalStateException("Something went wrong.")); StreamMessage<Void> transformed = streamMessage.mapError(ex -> { if (ex instanceof IllegalStateException) { return new MyDomainException(ex); } else { return ex; } }); -
peek
Peeks values emitted by thisStreamMessageand applies the specifiedConsumer.For example:
StreamMessage<Integer> source = StreamMessage.of(1, 2, 3, 4, 5); StreamMessage<Integer> ifEvenExistsThenThrow = source.peek(x -> { if (x % 2 == 0) { throw new IllegalArgumentException(); } }); -
peek
Peeks values emitted by thisStreamMessageand applies the specifiedConsumer. Only values which are an instance of the specifiedtypeare peeked.For example:
StreamMessage<Number> source = StreamMessage.of(0.1, 1, 0.2, 2, 0.3, 3); List<Integer> collected = new ArrayList<>(); List<Number> peeked = source.peek(x -> collected.add(x), Integer.class).collect().join(); assert collected.equals(List.of(1, 2, 3)); assert peeked.equals(List.of(0.1, 1, 0.2, 2, 0.3, 3)); -
peekError
Peeks an error emitted by thisStreamMessageand applies the specifiedConsumer.For example:
StreamMessage<Void> streamMessage = StreamMessage .aborted(new IllegalStateException("Something went wrong.")); StreamMessage<Void> peeked = streamMessage.peekError(ex -> { assert ex instanceof IllegalStateException; }); -
recoverAndResume
default StreamMessage<T> recoverAndResume(Function<? super Throwable, ? extends StreamMessage<T>> function) Recovers a failedStreamMessageand resumes by subscribing to a returned fallbackStreamMessagewhen any error occurs.Example:
StreamWriter<Integer> stream = StreamMessage.streaming(); stream.write(1); stream.write(2); stream.close(new IllegalStateException("Oops...")); StreamMessage<Integer> resumed = stream.recoverAndResume(cause -> StreamMessage.of(3, 4)); assert resumed.collect().join().equals(List.of(1, 2, 3, 4)); -
recoverAndResume
@UnstableApi default <E extends Throwable> StreamMessage<T> recoverAndResume(Class<E> causeClass, Function<? super E, ? extends StreamMessage<T>> function) Recovers a failedStreamMessageand resumes by subscribing to a returned fallbackStreamMessagewhen the thrownThrowableis the same type or a subtype of the specifiedcauseClass.Example:
StreamWriter<Integer> stream = StreamMessage.streaming(); stream.write(1); stream.write(2); stream.close(new IllegalStateException("Oops...")); StreamMessage<Integer> resumed = stream.recoverAndResume(IllegalStateException.class, cause -> StreamMessage.of(3, 4)); assert resumed.collect().join().equals(List.of(1, 2, 3, 4)); StreamWriter<Integer> stream = StreamMessage.streaming(); stream.write(1); stream.write(2); stream.write(3); stream.close(new IllegalStateException("test exception")); // Use the shortcut recover method as a chain. StreamMessage<Integer> recoverChain = stream.recoverAndResume(RuntimeException.class, cause -> { final IllegalArgumentException ex = new IllegalArgumentException("oops.."); // If a aborted StreamMessage returned from the first chain return StreamMessage.aborted(ex); }) // If the shortcut exception type is correct, catch and recover in the second chain. .recoverAndResume(IllegalArgumentException.class, cause -> StreamMessage.of(4, 5)); recoverChain.collect().join(); StreamWriter<Integer> stream = StreamMessage.streaming(); stream.write(1); stream.write(2); stream.close(ClosedStreamException.get()); // If the exception type does not match StreamMessage<Integer> mismatchRecovered = stream.recoverAndResume(IllegalStateException.class, cause -> StreamMessage.of(3, 4)); // In this case, CompletionException is thrown. (can't recover exception) mismatchRecovered.collect().join(); -
writeTo
default CompletableFuture<Void> writeTo(Function<? super T, ? extends HttpData> mapper, Path destination, OpenOption... options) Writes thisStreamMessageto the givenPathwithOpenOptions. If theOpenOptionis not specified, defaults toStandardOpenOption.CREATE,StandardOpenOption.TRUNCATE_EXISTINGandStandardOpenOption.WRITE.Example:
Path destination = Paths.get("foo.bin"); ByteBuf[] bufs = new ByteBuf[10]; for(int i = 0; i < 10; i++) { bufs[i] = Unpooled.wrappedBuffer(Integer.toString(i).getBytes()); } StreamMessage<ByteBuf> streamMessage = StreamMessage.of(bufs); streamMessage.writeTo(HttpData::wrap, destination).join(); assert Files.readString(destination).equals("0123456789"); -
toInputStream
Adapts thisStreamMessagetoInputStream.For example:
StreamMessage<String> streamMessage = StreamMessage.of("foo", "bar", "baz"); InputStream inputStream = streamMessage.toInputStream(x -> HttpData.wrap(x.getBytes())); byte[] expected = "foobarbaz".getBytes(); ByteBuf result = Unpooled.buffer(); int read; while ((read = inputStream.read()) != -1) { result.writeByte(read); } int readableBytes = result.readableBytes(); byte[] actual = new byte[readableBytes]; for (int i = 0; i < readableBytes; i++) { actual[i] = result.readByte(); } assert Arrays.equals(actual, expected); assert inputStream.available() == 0; -
toInputStream
default InputStream toInputStream(Function<? super T, ? extends HttpData> httpDataConverter, EventExecutor executor) Adapts thisStreamMessagetoInputStream.- Parameters:
executor- the executor to subscribe
-
endWith
@UnstableApi default StreamMessage<T> endWith(Function<@Nullable Throwable, ? extends @Nullable T> finalizer) Dynamically emits the last value depending on whether thisStreamMessagecompletes successfully or exceptionally.For example:
StreamMessage<Integer> source = StreamMessage.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); StreamMessage<Integer> aborted = source .peek(i -> { if (i > 5) { source.abort(); } }); StreamMessage<Integer> endWith = aborted .endWith(th -> { if (th instanceof AbortedStreamException) { return 100; } return -1; }); List<Integer> collected = endWith.collect().join(); assert collected.equals(List.of(1, 2, 3, 4, 5, 100));Note that if
nullis returned by theFunction, theStreamMessagewill complete successfully without emitting an additional value when this stream is complete successfully, or complete exceptionally when this stream is complete exceptionally. -
subscribeOn
Callssubscribe(Subscriber, EventExecutor)to the upstreamStreamMessageusing the specifiedEventExecutorand relays the stream transparently downstream. This may be useful if one would like to hide anEventExecutorfrom an upstreamPublisher.For example:
Subscriber<Integer> mySubscriber = null; StreamMessage<Integer> upstream = ...; // publisher callbacks are invoked by eventLoop1 upstream.subscribeOn(eventLoop1) .subscribe(mySubscriber, eventLoop2); // mySubscriber callbacks are invoked with eventLoop2
-
builder(Path)withPathStreamMessageBuilder.bufferSize(int)