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
- 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
Subscriber
consumes all elements andSubscriber.onComplete()
is invoked, - an error occurred and
Subscriber.onError(Throwable)
is invoked, - the
Subscription
has 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 TypeMethodDescriptionvoid
abort()
Closes this stream withAbortedStreamException
and prevents further subscription.void
Closes this stream with the specifiedThrowable
and prevents further subscription.static <T> StreamMessage<T>
Returns an abortedStreamMessage
that terminates with the specifiedThrowable
viaSubscriber.onError(Throwable)
immediately after being subscribed to.static PathStreamMessageBuilder
Returns a newPathStreamMessageBuilder
with 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 thisStreamMessage
with the specifiedSubscriptionOption
s.default CompletableFuture<List<T>>
collect
(EventExecutor executor, SubscriptionOption... options) Collects the elements published by thisStreamMessage
with the specifiedEventExecutor
andSubscriptionOption
s.static <T> StreamMessage<T>
Returns a concatenatedStreamMessage
which relays items of the specifiedPublisher
s 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 concatenatedStreamMessage
which relays items of the specifiedPublisher
ofPublisher
s in order, non-overlappingly, one after the other finishes.static <T> StreamMessage<T>
concat
(org.reactivestreams.Publisher<? extends T>... publishers) Returns a concatenatedStreamMessage
which relays items of the specified array ofPublisher
s in order, non-overlappingly, one after the other finishes.default <U> StreamMessage<U>
decode
(StreamDecoder<T, U> decoder) Creates a decodedStreamMessage
which is decoded from a stream ofT
type objects using the specifiedStreamDecoder
.default <U> StreamMessage<U>
decode
(StreamDecoder<T, U> decoder, ByteBufAllocator alloc) Creates a decodedStreamMessage
which is decoded from a stream ofT
type objects using the specifiedStreamDecoder
andByteBufAllocator
.default EventExecutor
Returns the defaultEventExecutor
which will be used when a user subscribes usingsubscribe(Subscriber)
,subscribe(Subscriber, SubscriptionOption...)
.long
demand()
Returns the current demand of this stream.default StreamMessage<T>
Filters values emitted by thisStreamMessage
.static ByteStreamMessage
fromOutputStream
(Consumer<? super OutputStream> outputStreamConsumer) static ByteStreamMessage
fromOutputStream
(Consumer<? super OutputStream> outputStreamConsumer, Executor blockingTaskExecutor) default boolean
Returnstrue
if this stream is complete, either successfully or exceptionally, including cancellation and abortion.boolean
isEmpty()
Returnstrue
if this stream has been closed and did not publish any elements.boolean
isOpen()
Returnstrue
if this stream is not closed yet.default <U> StreamMessage<U>
Transforms values emitted by thisStreamMessage
by applying the specifiedFunction
.default <U> StreamMessage<U>
mapAsync
(Function<? super T, ? extends CompletableFuture<? extends U>> function) Transforms values emitted by thisStreamMessage
by applying the specified asynchronousFunction
and emitting the value the future completes with.default StreamMessage<T>
Transforms an error emitted by thisStreamMessage
by applying the specifiedFunction
.default <U> StreamMessage<U>
mapParallel
(Function<? super T, ? extends CompletableFuture<? extends U>> function) Transforms values emitted by thisStreamMessage
by applying the specified asynchronousFunction
and 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 thisStreamMessage
by applying the specified asynchronousFunction
and emitting the value the future completes with.static <T> StreamMessage<T>
of()
Creates a newStreamMessage
that will publish no objects, just a close event.static ByteStreamMessage
Creates a newStreamMessage
that streams the specifiedFile
.static ByteStreamMessage
Creates a newStreamMessage
that streams the specifiedPath
.static ByteStreamMessage
Deprecated.static ByteStreamMessage
of
(Path path, @Nullable ExecutorService executor, ByteBufAllocator alloc, int bufferSize) static ByteStreamMessage
of
(Path path, ByteBufAllocator alloc, int bufferSize) Deprecated.static <T> StreamMessage<T>
of
(org.reactivestreams.Publisher<? extends T> publisher) Creates a newStreamMessage
from the specifiedPublisher
.static <T> StreamMessage<T>
of
(T obj) Creates a newStreamMessage
that will publish the singleobj
.static <T> StreamMessage<T>
of
(T... objs) Creates a newStreamMessage
that 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 thisStreamMessage
and applies the specifiedConsumer
.default <U extends T>
StreamMessage<T>Peeks values emitted by thisStreamMessage
and applies the specifiedConsumer
.default StreamMessage<T>
Peeks an error emitted by thisStreamMessage
and applies the specifiedConsumer
.default <E extends Throwable>
StreamMessage<T>recoverAndResume
(Class<E> causeClass, Function<? super E, ? extends StreamMessage<T>> function) Recovers a failedStreamMessage
and resumes by subscribing to a returned fallbackStreamMessage
when the thrownThrowable
is the same type or a subtype of the specifiedcauseClass
.default StreamMessage<T>
recoverAndResume
(Function<? super Throwable, ? extends StreamMessage<T>> function) Recovers a failedStreamMessage
and resumes by subscribing to a returned fallbackStreamMessage
when any error occurs.default CompletableFuture<Void>
Drains and discards all objects in thisStreamMessage
.default void
Requests to start streaming data to the specifiedSubscriber
.default void
subscribe
(org.reactivestreams.Subscriber<? super T> subscriber, SubscriptionOption... options) Requests to start streaming data to the specifiedSubscriber
.default void
subscribe
(org.reactivestreams.Subscriber<? super T> subscriber, EventExecutor executor) Requests to start streaming data to the specifiedSubscriber
.void
subscribe
(org.reactivestreams.Subscriber<? super T> subscriber, EventExecutor executor, SubscriptionOption... options) Requests to start streaming data to the specifiedSubscriber
.default StreamMessageDuplicator<T>
Returns a newStreamMessageDuplicator
that duplicates thisStreamMessage
into one or moreStreamMessage
s, which publish the same elements.default StreamMessageDuplicator<T>
toDuplicator
(EventExecutor executor) Returns a newStreamMessageDuplicator
that duplicates thisStreamMessage
into one or moreStreamMessage
s, which publish the same elements.default InputStream
toInputStream
(Function<? super T, ? extends HttpData> httpDataConverter) Adapts thisStreamMessage
toInputStream
.default InputStream
toInputStream
(Function<? super T, ? extends HttpData> httpDataConverter, EventExecutor executor) Adapts thisStreamMessage
toInputStream
.Returns aCompletableFuture
that completes when this stream is complete, either successfully or exceptionally, including cancellation and abortion.default CompletableFuture<Void>
-
Method Details
-
of
Creates a newStreamMessage
that will publish no objects, just a close event. -
of
Creates a newStreamMessage
that will publish the singleobj
. -
of
-
of
-
of
Creates a newStreamMessage
that will publish the givenobjs
. -
of
Creates a newStreamMessage
from the specifiedPublisher
. -
of
Creates a newStreamMessage
that streams the specifiedFile
. The default buffer size(8192) is used to create a buffer used to read data from theFile
. Therefore, the returnedStreamMessage
will emitHttpData
s chunked to size less than or equal to 8192. -
of
Creates a newStreamMessage
that streams the specifiedPath
. The default buffer size(8192) is used to create a buffer used to read data from thePath
. Therefore, the returnedStreamMessage
will emitHttpData
s chunked to size less than or equal to 8192. -
builder
Returns a newPathStreamMessageBuilder
with the specifiedPath
. -
of
Deprecated.Creates a newStreamMessage
that streams the specifiedPath
. The specifiedbufferSize
is used to create a buffer used to read data from thePath
. Therefore, the returnedStreamMessage
will emitHttpData
s chunked to size less than or equal tobufferSize
.- Parameters:
path
- the path of the filebufferSize
- the maximum allowed size of theHttpData
buffers
-
of
Deprecated.Creates a newStreamMessage
that streams the specifiedPath
. The specifiedbufferSize
is used to create a buffer used to read data from thePath
. Therefore, the returnedStreamMessage
will emitHttpData
s chunked to size less than or equal tobufferSize
.- Parameters:
path
- the path of the filealloc
- theByteBufAllocator
which will allocate the content bufferbufferSize
- the maximum allowed size of theHttpData
buffers
-
of
@Deprecated static ByteStreamMessage of(Path path, @Nullable @Nullable ExecutorService executor, ByteBufAllocator alloc, int bufferSize) Deprecated.Creates a newStreamMessage
that streams the specifiedPath
. The specifiedbufferSize
is used to create a buffer used to read data from thePath
. Therefore, the returnedStreamMessage
will emitHttpData
s chunked to size less than or equal tobufferSize
.- Parameters:
path
- the path of the fileexecutor
- theExecutorService
which performs blocking IO readalloc
- theByteBufAllocator
which will allocate the content bufferbufferSize
- the maximum allowed size of theHttpData
buffers
-
fromOutputStream
Creates a newByteStreamMessage
that publishesHttpData
s 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
, theOutputStream
is closed by theStreamMessage
and the exception is propagated to theSubscriber
automatically. -
fromOutputStream
static ByteStreamMessage fromOutputStream(Consumer<? super OutputStream> outputStreamConsumer, Executor blockingTaskExecutor) Creates a newByteStreamMessage
that publishesHttpData
s 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
, theOutputStream
is closed by theStreamMessage
and the exception is propagated to theSubscriber
automatically.- 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 concatenatedStreamMessage
which relays items of the specified array ofPublisher
s 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 concatenatedStreamMessage
which relays items of the specifiedPublisher
s 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 concatenatedStreamMessage
which relays items of the specifiedPublisher
ofPublisher
s in order, non-overlappingly, one after the other finishes. -
aborted
Returns an abortedStreamMessage
that terminates with the specifiedThrowable
viaSubscriber.onError(Throwable)
immediately after being subscribed to. -
isOpen
boolean isOpen()Returnstrue
if 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()Returnstrue
if this stream has been closed and did not publish any elements. Note that this method will not returntrue
when 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()Returnstrue
if this stream is complete, either successfully or exceptionally, including cancellation and abortion.A
StreamMessage
is complete (or 'fully consumed') when:- the
Subscriber
consumes all elements andSubscriber.onComplete()
is invoked, - an error occurred and
Subscriber.onError(Throwable)
is invoked, - the
Subscription
has been cancelled or abort()
has been requested.
- the
-
whenComplete
CompletableFuture<Void> whenComplete()Returns aCompletableFuture
that completes when this stream is complete, either successfully or exceptionally, including cancellation and abortion.A
StreamMessage
is complete (or 'fully consumed') when:- the
Subscriber
consumes all elements andSubscriber.onComplete()
is invoked, - an error occurred and
Subscriber.onError(Throwable)
is invoked, - the
Subscription
has 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
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:IllegalStateException
if otherSubscriber
subscribed to this stream already.AbortedStreamException
if this stream has been aborted.CancelledSubscriptionException
if this stream has been cancelled andSubscriptionOption.NOTIFY_CANCELLATION
is specified when subscribed.- Other exceptions that occurred due to an error while retrieving the elements.
- Specified by:
subscribe
in 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:IllegalStateException
if otherSubscriber
subscribed to this stream already.AbortedStreamException
if this stream has been aborted.CancelledSubscriptionException
if this stream has been cancelled andSubscriptionOption.NOTIFY_CANCELLATION
is specified when subscribed.- Other exceptions that occurred due to an error while retrieving the elements.
- Parameters:
options
-SubscriptionOption
s 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:IllegalStateException
if otherSubscriber
subscribed to this stream already.AbortedStreamException
if this stream has been aborted.CancelledSubscriptionException
if this stream has been cancelled andSubscriptionOption.NOTIFY_CANCELLATION
is 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:IllegalStateException
if otherSubscriber
subscribed to this stream already.AbortedStreamException
if this stream has been aborted.CancelledSubscriptionException
if this stream has been cancelled andSubscriptionOption.NOTIFY_CANCELLATION
is specified when subscribed.- Other exceptions that occurred due to an error while retrieving the elements.
- Parameters:
executor
- the executor to subscribeoptions
-SubscriptionOption
s to subscribe with
-
toDuplicator
Returns a newStreamMessageDuplicator
that duplicates thisStreamMessage
into one or moreStreamMessage
s, which publish the same elements. Note that you cannot subscribe to thisStreamMessage
anymore after you call this method. To subscribe, callStreamMessageDuplicator.duplicate()
from the returnedStreamMessageDuplicator
. -
toDuplicator
Returns a newStreamMessageDuplicator
that duplicates thisStreamMessage
into one or moreStreamMessage
s, which publish the same elements. Note that you cannot subscribe to thisStreamMessage
anymore after you call this method. To subscribe, callStreamMessageDuplicator.duplicate()
from the returnedStreamMessageDuplicator
.- Parameters:
executor
- the executor to duplicate
-
defaultSubscriberExecutor
Returns the defaultEventExecutor
which will be used when a user subscribes usingsubscribe(Subscriber)
,subscribe(Subscriber, SubscriptionOption...)
.Please note that if this method is called multiple times, the returned
EventExecutor
s can be different depending on thisStreamMessage
implementation. -
abort
void abort()Closes this stream withAbortedStreamException
and prevents further subscription. ASubscriber
that attempts to subscribe to an aborted stream will be notified with anAbortedStreamException
viaSubscriber.onError(Throwable)
. Calling this method on a closed or aborted stream has no effect. -
abort
-
decode
Creates a decodedStreamMessage
which is decoded from a stream ofT
type objects using the specifiedStreamDecoder
. -
decode
@UnstableApi default <U> StreamMessage<U> decode(StreamDecoder<T, U> decoder, ByteBufAllocator alloc) Creates a decodedStreamMessage
which is decoded from a stream ofT
type objects using the specifiedStreamDecoder
andByteBufAllocator
. -
collect
Collects the elements published by thisStreamMessage
. The returnedCompletableFuture
will be notified when the elements are fully consumed.Note that if this
StreamMessage
was subscribed by otherSubscriber
already, the returnedCompletableFuture
will 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 thisStreamMessage
with the specifiedSubscriptionOption
s. The returnedCompletableFuture
will be notified when the elements are fully consumed.Note that if this
StreamMessage
was subscribed by otherSubscriber
already, the returnedCompletableFuture
will be completed with anIllegalStateException
. -
collect
Collects the elements published by thisStreamMessage
with the specifiedEventExecutor
andSubscriptionOption
s. The returnedCompletableFuture
will be notified when the elements are fully consumed.Note that if this
StreamMessage
was subscribed by otherSubscriber
already, the returnedCompletableFuture
will be completed with anIllegalStateException
. -
filter
Filters values emitted by thisStreamMessage
. If thePredicate
test succeeds, the value is emitted. If thePredicate
test fails, the value is ignored and a request of1
is 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 thisStreamMessage
by applying the specifiedFunction
. As per Reactive Streams Specification 2.13, the specifiedFunction
should not return anull
value.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 thisStreamMessage
by applying the specified asynchronousFunction
and emitting the value the future completes with. TheStreamMessage
publishes items in order, non-overlappingly, one after the other finishes. As per Reactive Streams Specification 2.13, the specifiedFunction
should not return anull
value nor a future which completes with anull
value.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 thisStreamMessage
by applying the specified asynchronousFunction
and emitting the value the future completes with. TheStreamMessage
publishes 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 specifiedFunction
should not return anull
value nor a future which completes with anull
value.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 thisStreamMessage
by applying the specified asynchronousFunction
and emitting the value the future completes with. TheStreamMessage
publishes items eagerly in the order that the futures complete. The number of pending futures will at most bemaxConcurrency
It does not necessarily preserve the order of the original stream. As per Reactive Streams Specification 2.13, the specifiedFunction
should not return anull
value nor a future which completes with anull
value.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 thisStreamMessage
by applying the specifiedFunction
. As per Reactive Streams Specification 2.13, the specifiedFunction
should not return anull
value.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 thisStreamMessage
and 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 thisStreamMessage
and applies the specifiedConsumer
. Only values which are an instance of the specifiedtype
are 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 thisStreamMessage
and 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 failedStreamMessage
and resumes by subscribing to a returned fallbackStreamMessage
when any error occurs.Example:
DefaultStreamMessage<Integer> stream = new DefaultStreamMessage<>(); 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 failedStreamMessage
and resumes by subscribing to a returned fallbackStreamMessage
when the thrownThrowable
is the same type or a subtype of the specifiedcauseClass
.Example:
DefaultStreamMessage<Integer> stream = new DefaultStreamMessage<>(); 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)); DefaultStreamMessage<Integer> stream = new DefaultStreamMessage<>(); 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(); DefaultStreamMessage<Integer> stream = new DefaultStreamMessage<>(); 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 thisStreamMessage
to the givenPath
withOpenOption
s. If theOpenOption
is not specified, defaults toStandardOpenOption.CREATE
,StandardOpenOption.TRUNCATE_EXISTING
andStandardOpenOption.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 thisStreamMessage
toInputStream
.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 thisStreamMessage
toInputStream
.- Parameters:
executor
- the executor to subscribe
-
builder(Path)
withPathStreamMessageBuilder.bufferSize(int)