Interface Streamable<T>
- Type Parameters:
T- the element type of theStreamablesequence.
- All Known Subinterfaces:
StreamProcessor<In,Out>
- All Known Implementing Classes:
DispatchStreamProcessor, GroupedStreamable
- Functional Interface:
- This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
Represents a virtual-thread capable, multi-valued (a)synchronous sequence of values that
builds upon the Java CompletionStage-based concurrency-coordination model.
The lifecycle of the sequence is as follows:
- consumer calls
stream(StreamerCancellation) - consumer calls
Streamer.next()in a loop and consumer checks if what theCompletionStageoutcome is:- if it succeeded with a boolean
true, it is safe to callStreamer.current(). - if it succeeded with a boolean
false, no further values are coming. - if it failed with a
Throwable, no further values are coming and the error can be propagated further
- if it succeeded with a boolean
- consumer calls
Streamer.finish()
It is always necessary to have the consumer call finish because that is responsible for cleaning up
resources of the upstream.
Downstream cancellations are signaled via the StreamerCancellation, where operators can register their own
Disposables that get disposed. Because dispose can happen at any time and asynchronously to the consumption loop,
the sensitive sources must complete their waiting CompletionStage returned by next exceptionally via a
CancellationException. This will unblock the loops and invoke the finish method of the lifecycle at
the consumer thread. Depending on the operator, the CancellationException may not be propagated further.
If a source wishes to fail, it must signal the Throwable via the returned CompletionStage of next.
If the finish also throws, its Throwable should be added as suppressed exception to the original Throwable.
The Streamer methods must be invoked sequentially and non-overlappingly, similar to the
Reactive Streams rule ยง1.3.
This reactive type was modeled after the C# IAsyncEnumerable and IAsyncEnumerator interfaces. Unfortunately,
Java never added any async/await infrastructure, plus CompletionStage doesn't even have any native way to blockingly
join to it. Therefore, when running in a (virtual) blocking fashion, one may use the Streamer.awaitNext()
or Streamer.awaitFinish() helper methods.
- Since:
- 4.0.0
-
Method Summary
Modifier and TypeMethodDescriptiondefault TBlocks the current thread until thisStreamableproduces one item, which is then returned.default TBlocks the current thread until thisStreamableproduces all of its items and the very last is then returned.default <A,R> @NonNull Streamable <R> Collects all upstream values via the use of aCollectorconfiguration and emits its resulting value as a single item of the returnedStreamable.static <@NonNull T>
@NonNull Streamable<T> concat(Streamable<? extends Streamable<? extends @NonNull T>> sources, ExecutorService executor) Emits the elements of each inner sequence produced by the outer sequence.static <@NonNull T>
@NonNull Streamable<T> concat(Iterable<? extends Streamable<? extends @NonNull T>> sources) Streams theStreamables one after the other from the given iterable sequence ofStreamables.static <@NonNull T>
@NonNull Streamable<T> create(@NonNull VirtualGenerator<@NonNull T> generator) Generate a sequence of values via a virtual generator callback (yielder) which is free to block and is natively backpressured.static <@NonNull T>
@NonNull Streamable<T> Generate a sequence of values via a virtual generator callback (yielder) which is free to block and is natively backpressured.static <@NonNull T>
@NonNull Streamable<T> create(@NonNull VirtualGenerator<@NonNull T> generator, @NonNull ExecutorService executor) Generate a sequence of values via a virtual generator callback (yielder) which is free to block and is natively backpressured.static <@NonNull T>
@NonNull Streamable<T> defer(Supplier<? extends Streamable<? extends @NonNull T>> supplier) Defers the creation of the actualStreamable, allowing a per streamer state to be created along with it.default @NonNull Streamable<T> Delays the delivery of each upstream item by the given time amount.default @NonNull Streamable<T> Calls the specificConsumerif there is an error from the upstream.default @NonNull Streamable<T> Calls the given consumer whenever an upstream item becomes available.static <@NonNull T>
@NonNull Streamable<T> empty()Returns an emptyStreamablethat never produces an item and just completes.static <@NonNull T>
@NonNull Streamable<T> Creates aStreamablethat signals the givenThrowableimmediately when it begins streaming, ending the sequence.default @NonNull Streamable<T> Filters out the upstream items that do not pass the given predicate.default <R> @NonNull Streamable<R> flatMap(@NonNull Function<? super @NonNull T, ? extends Streamable<? extends R>> mapper, @NonNull StandardConcurrentConfig config) Maps each upstream item onto aStreamableand runs them concurrently while relaying inner items as first-come-first-served manner.default @NonNull CompletionStageDisposable<Void> forEach(@NonNull BiConsumer<? super @NonNull T, ? super Disposable> consumer, @NonNull DisposableStreamerCancellation canceller, @NonNull ExecutorService executor) Consumes elements from thisStreamablevia the provided executor service.default @NonNull CompletionStageDisposable<Void> Consumes elements from thisStreamablevia the provided executor service.default @NonNull CompletionStageDisposable<Void> forEach(@NonNull Consumer<? super @NonNull T> consumer, @NonNull DisposableStreamerCancellation canceller) Consumes elements from thisStreamablevia the provided executor service.default @NonNull CompletionStageDisposable<Void> forEach(@NonNull Consumer<? super @NonNull T> consumer, @NonNull DisposableStreamerCancellation canceller, @NonNull ExecutorService executor) Consumes elements from thisStreamablevia the provided executor service.default @NonNull CompletionStageDisposable<Void> Consumes elements from thisStreamablevia the provided executor service.static <@NonNull T>
@NonNull Streamable<T> Streams all elements of the given items array.static <@NonNull T>
Streamable<T> fromCompletable(@NonNull CompletableSource source) Convert aCompletableSourceinto aStreamableand relay its terminal events.static <@NonNull T>
@NonNull Streamable<T> fromIterable(@NonNull Iterable<? extends @NonNull T> items) Streams all elements of the givenIterablesequence.static <@NonNull T>
Streamable<T> fromMaybe(@NonNull MaybeSource<@NonNull T> source) Convert aMaybeSourceinto aStreamableand relay its terminal events.static <T> @NonNull Streamable<T> fromPublisher(Flow.Publisher<T> source) Convert anyFlow.Publisherinto aStreamablesequence.static <T> @NonNull Streamable<T> fromPublisher(Flow.Publisher<T> source, @NonNull ExecutorService executor) Convert anyFlow.Publisherinto aStreamablesequence.static <@NonNull T>
Streamable<T> fromSingle(@NonNull SingleSource<@NonNull T> source) Convert aSingleSourceinto aStreamableand relay its terminal events.static <@NonNull T>
@NonNull Streamable<T> fromStream(@NonNull Stream<? extends @NonNull T> items) Streams all elements of the givenStreamsequence.default <@Nullable K>
@NonNull Streamable<GroupedStreamable<K, T>> Maps each upstream item into aGroupedStreamablegroup, emits those groups and keeps relaying the upstream items into those groups.default @NonNull Streamable<T> hide()Hides the identity of thisStreamableand itsStreamer.default @NonNull Streamable<T> Ignores all elements from the currentStreamableand completes.default @NonNull Streamable<T> intercept(StreamableInterceptConfig<@NonNull T> config) Intercepts the lifecycle method calls ofStreamableandStreamerand allows the modification of them via Function callbacks.static Streamable<Long> intervalRange(long start, long count, long initialDelay, long period, TimeUnit unit, Scheduler scheduler) Constructs aStreamablethat after the initial delay, starts emitting an ever increasing numbers fromstartup tostart + countexclusive with the given period.static Streamable<Long> intervalRange(long start, long count, long initialDelay, long period, TimeUnit unit, ExecutorService executor) Constructs aStreamablethat after the initial delay, starts emitting an ever increasing numbers fromstartup tostart + countexclusive with the given period.static <@NonNull T>
@NonNull Streamable<T> Returns a single-elementStreamablethat produces the constant item and completes.Signals the last item from the upstreamStreamableor the provideddefaultItemif the upstream is empty, as aSingleinstance.Signals the last item from the upstreamStreamableor aNoSuchElementExceptionif the upstream is empty, as aSingleinstance.default <@NonNull R>
@NonNull Streamable<R> This method requires advanced knowledge about building operators, please consider other standard composition methods first; Returns aStreamableinstance which when itsstream(StreamerCancellation)is invoked, applies the specified operator callback to the upstreamStreamerto produce an actualStreamerinstance to be handed downstream.default <@NonNull R>
@NonNull Streamable<R> Maps each upstream item into another item via a mapper function.default <@NonNull R>
@NonNull Streamable<R> Maps each upstream item into another, optional item via a mapper function that skips the empty optionals.static <@NonNull T>
@NonNull Streamable<T> never()Returns anStreamablethat never produces an item and never terminates.default @NonNull Streamable<T> onErrorResumeNext(@NonNull Function<? super Throwable, ? extends Streamable<? extends @NonNull T>> fallbackMapper) When the upstream fails, the sequence is resumed by theStreamablethat is returned for the failureThrowable.static @NonNull Streamable<Integer> range(int start, int count) Emits elements from start up to start + count exclusive.static @NonNull Streamable<Long> rangeLong(long start, long count) Emits elements from start up to start + count exclusive.default @NonNull Streamable<T> repeat(long count) Runs the upstream at most the givencounttimes while it succeeds.default @NonNull Streamable<T> repeatWhen(Function<? super Long, ? extends CompletionStage<Boolean>> whenFunction) Repeats the upstream when the given function signalstruevia theCompletionStagefor the count how many times the upstream was streamed.default @NonNull Streamable<T> retry(long count) Retries at most the givencounttimes the upstream if it fails with any error.default @NonNull Streamable<T> retry(BiPredicate<? super Long, ? super Throwable> predicate) Retries the upstream if the given predicate returnstruefor the failure count andThrowableof the last streaming of the upstream.default @NonNull Streamable<T> Retries the upstream if the given predicate returnstruefor the failureThrowableof the last streaming of the upstream.default @NonNull Streamable<T> retryWhen(BiFunction<? super Long, ? super Throwable, ? extends CompletionStage<Boolean>> whenFunction) Retries the upstream when the given predicate signalstruevia theCompletionStagefor the failure count andThrowableof the last streaming of the upstream.default @NonNull Streamable<T> skip(long count) Skips the firstcountitems and relays the rest to the downstream.stream(@NonNull StreamerCancellation cancellation) Realizes the stream and returns an interface that lets one consume it.default @NonNull CompletionStage<Void> subscribe(@NonNull StreamSink<? super @NonNull T> consumer) Relays the events of the upstream into aStreamSinkconsumer via the help of the standardExecutors.newVirtualThreadPerTaskExecutor()as a mediator for pull-to-push.default @NonNull CompletionStage<Void> subscribe(@NonNull StreamSink<? super @NonNull T> consumer, ExecutorService executor) Relays the events of the upstream into aStreamSinkconsumer via the help of the givenExecutorServiceas a mediator for pull-to-push.default voidsubscribe(Flow.Subscriber<? super @NonNull T> subscriber) Consume thisStreamablevia the given flow-reactive-streams subscriber on a virtual thread backed executor service.default voidsubscribe(Flow.Subscriber<? super @NonNull T> subscriber, @NonNull ExecutorService executor) Consume thisStreamablevia the given flow-reactive-streams subscriber.default @NonNull Streamable<T> take(long count) Takes at most the given number of items from the upstream and relays it to the downstream, then cancels the rest of the sequence.default <U> @NonNull Streamable<T> takeUntil(@NonNull Streamable<U> other) Relays items from thisStreamableuntil the otherStreamablesignals an item or completes.default @NonNull Streamable<T> Relays items from thisStreamablewhile the predicate returnstruedefault @NonNull TestSubscriber<T> test()Creates a newTestSubscriberand subscribes it to thisStreamable.default @NonNull TestSubscriber<T> test(@NonNull ExecutorService executor) Creates a newTestSubscriberand subscribes it to thisStreamable.default @NonNull Streamable<T> timeout(long timeout, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, @NonNull Streamable<@NonNull T> fallback) Applies a timeout to each upstream item and switches to the fallbackStreamableif the upstream doesn't produce an item within the given timeout period.static @NonNull Streamable<Long> Signals a single 0L and completes after the given delay amount of time.static @NonNull Streamable<Long> timer(long delay, TimeUnit unit, ExecutorService executor) Signals a single 0L and completes after the given delay amount of time.default <@NonNull R>
RCalls the specified converter function during assembly time and returns its resulting value.Converts the streamable into a Flowable representation, running on the default Executors.newVirtualThreadPerTaskExecutor() virtual thread.toFlowable(@NonNull ExecutorService executor) Converts thisStreamableinto aFlowablerepresentation, running on the provided executor service.default @NonNull Observable<T> Converts thisStreamableinto aObservablerepresentation, emitting items on whatever thread produces items in the currentStreamable.default <@NonNull R>
@NonNull Streamable<R> Transforms the upstream sequence into zero or more elements for the downstream.default <@NonNull R>
@NonNull Streamable<R> transform(@NonNull VirtualTransformer<@NonNull T, @NonNull R> transformer, @NonNull ExecutorService executor) Transforms the upstream sequence into zero or more elements for the downstream.static <T,R> @NonNull Streamable <T> using(Supplier<? extends R> resourceSupplier, Function<? super R, ? extends Streamable<? extends T>> resourceMapper, Consumer<? super R> resourceCleaner) For each incoming streamer, this operator creates a resource, then uses that resource to create the actualStreamableinstance to stream value of and then uses a cleaner callback to dissolve the resource once theStreamableterminated.static <T> @NonNull Streamable<List<T>> zip(Iterable<? extends Streamable<? extends T>> sources) Takes the next element from each sourceStreamableand emits them a a single row ofList.
-
Method Details
-
stream
@CheckReturnValue @NonNull @NonNull Streamer<T> stream(@NonNull @NonNull StreamerCancellation cancellation) Realizes the stream and returns an interface that lets one consume it.Implementations are not meant to dispose the
cancellationas it is the privilege of whatever calls thestreammethod. If you need to talk to otherStreamables, use theStreamerCancellation.derive()to gain access to a fully fledgedDisposableStreamerCancellationwhere you can dispose it without disposing the parentcancellationinstance by accident.It is recommened you
StreamerCancellation.remove(Disposable)orStreamerCancellation.delete(Disposable)any extra resources you added viaStreamerCancellation.add(Disposable)when your operator reaches theStreamer.finish()call.- Parameters:
cancellation- where to register, check and listen for cancellation calls via itsStreamerCancellation.isDisposed()- Returns:
- the Streamer instance to consume.
-
concat
@CheckReturnValue @NonNull static <@NonNull T> @NonNull Streamable<T> concat(Streamable<? extends Streamable<? extends @NonNull T>> sources, ExecutorService executor) Emits the elements of each inner sequence produced by the outer sequence.- Type Parameters:
T- the common element type- Parameters:
sources- a streamable of inner streamablesexecutor- the executorservice where to run the virtual wait- Returns:
- the new
Streamableinstance. - Throws:
NullPointerException- ifsourcesorexecutorisnull
-
concat
@CheckReturnValue @NonNull static <@NonNull T> @NonNull Streamable<T> concat(Iterable<? extends Streamable<? extends @NonNull T>> sources) Streams theStreamables one after the other from the given iterable sequence ofStreamables.- Type Parameters:
T- the element type of the inner and resultingStreamables- Parameters:
sources- the iterable sequence ofStreamables.- Returns:
- the new
Streamablesource - Throws:
NullPointerException- ifsourcesisnull
-
create
@CheckReturnValue @NonNull static <@NonNull T> @NonNull Streamable<T> create(@NonNull @NonNull VirtualGenerator<@NonNull T> generator) Generate a sequence of values via a virtual generator callback (yielder) which is free to block and is natively backpressured.Runs on the
Schedulers.virtual()scheduler.Example
Streamable.create(emitter -> { emitter.emit(1); emitter.emit(2); emitter.emit(3); }) .forEach(System.out::println) ;- Type Parameters:
T- the element type- Parameters:
generator- the generator to use- Returns:
- the streamable instance
-
create
@CheckReturnValue @NonNull static <@NonNull T> @NonNull Streamable<T> create(@NonNull @NonNull VirtualGenerator<@NonNull T> generator, @NonNull @NonNull Scheduler scheduler) Generate a sequence of values via a virtual generator callback (yielder) which is free to block and is natively backpressured.Runs on the given scheduler.
Example
Streamable.create(emitter -> { emitter.emit(1); emitter.emit(2); emitter.emit(3); }, Schedulers.cached()) .forEach(System.out::println) ;- Type Parameters:
T- the element type- Parameters:
generator- the generator to usescheduler- the scheduler to run the virtual generator on- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifgeneratororschedulerisnull
-
create
@CheckReturnValue @NonNull static <@NonNull T> @NonNull Streamable<T> create(@NonNull @NonNull VirtualGenerator<@NonNull T> generator, @NonNull @NonNull ExecutorService executor) Generate a sequence of values via a virtual generator callback (yielder) which is free to block and is natively backpressured.Runs on the given executor service.
- Type Parameters:
T- the element type- Parameters:
generator- the generator to useexecutor- the executor to run the virtual generator on- Returns:
- the streamable instance
-
defer
@CheckReturnValue @NonNull static <@NonNull T> @NonNull Streamable<T> defer(Supplier<? extends Streamable<? extends @NonNull T>> supplier) Defers the creation of the actualStreamable, allowing a per streamer state to be created along with it.- Type Parameters:
T- the element type of theStreamable- Parameters:
supplier- the callback that returns the actualStreamableto be streamed- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifsupplierisnull
-
error
Creates aStreamablethat signals the givenThrowableimmediately when it begins streaming, ending the sequence.- Type Parameters:
T- the element type of the sequence- Parameters:
throwable- theThrowableto signal immediately upon streaming- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifthrowableisnull
-
empty
Returns an emptyStreamablethat never produces an item and just completes.- Type Parameters:
T- the element type- Returns:
- the
Streamableinstance
-
filter
@CheckReturnValue @NonNull default @NonNull Streamable<T> filter(@NonNull @NonNull Predicate<? super @NonNull T> predicate) Filters out the upstream items that do not pass the given predicate.- Parameters:
predicate- the callback that should returntrueto let the upstream value pass orfalseto ignore it and continue with the next upstream item- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifpredicateisnull
-
fromArray
@SafeVarargs @CheckReturnValue @NonNull static <@NonNull T> @NonNull Streamable<T> fromArray(@NonNull @NonNull T... items) Streams all elements of the given items array.- Type Parameters:
T- the element type of the items- Parameters:
items- the array of items to stream- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifitemsisnull
-
fromCompletable
Convert aCompletableSourceinto aStreamableand relay its terminal events.The resulting
Streamablewill never produce any items.- Type Parameters:
T- the target type of the sequence- Parameters:
source- the sourceCompletableSourceto convert- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifsourceisnull
-
fromIterable
@CheckReturnValue @NonNull static <@NonNull T> @NonNull Streamable<T> fromIterable(@NonNull @NonNull Iterable<? extends @NonNull T> items) Streams all elements of the givenIterablesequence.- Type Parameters:
T- the element type of the items- Parameters:
items- the iterable of items to stream- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifitemsisnull
-
fromMaybe
Convert aMaybeSourceinto aStreamableand relay its terminal events.The resulting
Streamablewill never produce any items.- Type Parameters:
T- the target type of the sequence- Parameters:
source- the sourceMaybeSourceto convert- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifsourceisnull
-
fromPublisher
@CheckReturnValue @NonNull static <T> @NonNull Streamable<T> fromPublisher(@NonNull Flow.Publisher<T> source) Convert anyFlow.Publisherinto aStreamablesequence.- Type Parameters:
T- the element type- Parameters:
source- Flow.Publisher to convert- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifsourceisnull
-
fromPublisher
@CheckReturnValue @NonNull static <T> @NonNull Streamable<T> fromPublisher(@NonNull Flow.Publisher<T> source, @NonNull @NonNull ExecutorService executor) Convert anyFlow.Publisherinto aStreamablesequence.- Type Parameters:
T- the element type- Parameters:
source- Flow.Publisher to convertexecutor- where the conversion will run- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifsourceorexecutorisnull
-
fromSingle
Convert aSingleSourceinto aStreamableand relay its terminal events.The resulting
Streamablewill never produce any items.- Type Parameters:
T- the target type of the sequence- Parameters:
source- the sourceSingleSourceto convert- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifsourceisnull
-
fromStream
@CheckReturnValue @NonNull static <@NonNull T> @NonNull Streamable<T> fromStream(@NonNull @NonNull Stream<? extends @NonNull T> items) Streams all elements of the givenStreamsequence.- Type Parameters:
T- the element type of the items- Parameters:
items- the stream of items to stream- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifitemsisnull
-
intervalRange
static Streamable<Long> intervalRange(long start, long count, long initialDelay, long period, TimeUnit unit, Scheduler scheduler) Constructs aStreamablethat after the initial delay, starts emitting an ever increasing numbers fromstartup tostart + countexclusive with the given period.If there are processing delays, this source may emit multiple queued up items in a quick succession.
- Parameters:
start- the first long value to emitcount- the number of items to emit, useLong.MAX_VALUEfor an unlimited rangeinitialDelay- the time to delay before thestartitem is emittedperiod- the period of how often emit the next itemunit- the time unit for bothinitialDelayandperiodscheduler- the scheduler to use for the timed waiting- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifunitorschedulerisnullIllegalArgumentException- ifcountis negative
-
intervalRange
static Streamable<Long> intervalRange(long start, long count, long initialDelay, long period, TimeUnit unit, ExecutorService executor) Constructs aStreamablethat after the initial delay, starts emitting an ever increasing numbers fromstartup tostart + countexclusive with the given period.If the provided
ExecutorServiceis aScheduledExecutorService, itsScheduledExecutorService.scheduleAtFixedRate(Runnable, long, long, TimeUnit)will be used. Otherwise, a plainExecutorServicewill be wrapped viaSchedulers.from(Executor).If there are processing delays, this source may emit multiple queued up items in a quick succession.
- Parameters:
start- the first long value to emitcount- the number of items to emit, useLong.MAX_VALUEfor an unlimited rangeinitialDelay- the time to delay before thestartitem is emittedperiod- the period of how often emit the next itmeunit- the time unit for bothinitialDelayandperiodexecutor- the executor to use- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifunitorexecutorisnullIllegalArgumentException- ifcountis negative
-
just
@CheckReturnValue @NonNull static <@NonNull T> @NonNull Streamable<T> just(@NonNull @NonNull T item) Returns a single-elementStreamablethat produces the constant item and completes.- Type Parameters:
T- the element type- Parameters:
item- the constant item to produce- Returns:
- the
Streamableinstance - Throws:
NullPointerException- ifitemisnull
-
never
Returns anStreamablethat never produces an item and never terminates.- Type Parameters:
T- the element type- Returns:
- the
Streamableinstance
-
range
Emits elements from start up to start + count exclusive.- Parameters:
start- the start elementcount- the number of elements to emit- Returns:
- the new
Streamableinstance - Throws:
IllegalArgumentException- ifcountis negative
-
rangeLong
Emits elements from start up to start + count exclusive.- Parameters:
start- the start elementcount- the number of elements to emit- Returns:
- the new
Streamableinstance - Throws:
IllegalArgumentException- ifcountis negative
-
timer
@CheckReturnValue @NonNull static @NonNull Streamable<Long> timer(long delay, TimeUnit unit, Scheduler scheduler) Signals a single 0L and completes after the given delay amount of time.- Parameters:
delay- the amount to delay the signaling of a single itemunit- the time unitscheduler- where the timed delay should happen- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifunitorschedulerisnull
-
timer
@CheckReturnValue @NonNull static @NonNull Streamable<Long> timer(long delay, TimeUnit unit, ExecutorService executor) Signals a single 0L and completes after the given delay amount of time.If the
executoris aScheduledExecutorService, the operator will use itsScheduledExecutorService.schedule(Runnable, long, TimeUnit)method. Otherwise, theExecutorService.submit(Callable)will be invoked with an upfrontTimeUnit.sleep(long).- Parameters:
delay- the amount to delay the signaling of a single itemunit- the time unitexecutor- where the timed delay should happen- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifunitorexecutorisnull
-
using
@CheckReturnValue @NonNull static <T,R> @NonNull Streamable<T> using(Supplier<? extends R> resourceSupplier, Function<? super R, ? extends Streamable<? extends T>> resourceMapper, Consumer<? super R> resourceCleaner) For each incoming streamer, this operator creates a resource, then uses that resource to create the actualStreamableinstance to stream value of and then uses a cleaner callback to dissolve the resource once theStreamableterminated.- Type Parameters:
T- the element type of the sequenceR- the resource type- Parameters:
resourceSupplier- supplies a resource object perstream(StreamerCancellation)callresourceMapper- maps the supplied resource into aStreamablesourceresourceCleaner- cleans up the supplied resource- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifresourceSupplierorresourceMapperorresourceCleanerisnull
-
zip
@CheckReturnValue @NonNull static <T> @NonNull Streamable<List<T>> zip(Iterable<? extends Streamable<? extends T>> sources) Takes the next element from each sourceStreamableand emits them a a single row ofList.If any of the sources is shorter than the rest or any of them fails, the sequence is completed early normally or with an exception, respectively.
- Type Parameters:
T- the common element type of the sequences- Parameters:
sources- theIterablesequence of the sourceStreamables- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifsourcesisnull
-
blockingFirst
Blocks the current thread until thisStreamableproduces one item, which is then returned.- Returns:
- the first item of this
Streamable - Throws:
NoSuchElementException- if the thisStreamableis emptyCancellationException- if thisStreamablefailed with a checked exceptionRuntimeException- if thisStreamablefailed with an unchecked exception
-
blockingLast
Blocks the current thread until thisStreamableproduces all of its items and the very last is then returned.- Returns:
- the very last item of this
Streamable - Throws:
NoSuchElementException- if the thisStreamableis emptyCancellationException- if thisStreamablefailed with a checked exceptionRuntimeException- if thisStreamablefailed with an unchecked exception
-
collect
@CheckReturnValue @NonNull default <A,R> @NonNull Streamable<R> collect(@NonNull @NonNull Collector<@NonNull T, A, R> collector) Collects all upstream values via the use of aCollectorconfiguration and emits its resulting value as a single item of the returnedStreamable.See
Collectorsfor the most typical collector standard implementations.- Type Parameters:
A- the accumulator type of the collectorR- the result type of the collector and the returnedStreamamble- Parameters:
collector- the Java collector instance to use- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifcollectorisnull
-
delay
@CheckReturnValue @NonNull default @NonNull Streamable<T> delay(long time, @NonNull @NonNull TimeUnit unit, @NonNull @NonNull Scheduler scheduler) Delays the delivery of each upstream item by the given time amount.- Parameters:
time- the delay timeunit- the time unitscheduler- the scheduler where the timed wait is happening- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifunitorschedulerisnull
-
doOnError
@CheckReturnValue @NonNull default @NonNull Streamable<T> doOnError(@NonNull @NonNull Consumer<? super Throwable> consumer) Calls the specificConsumerif there is an error from the upstream.- Parameters:
consumer- the consumer to call with the Throwable- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifconsumerisnull
-
doOnNext
@CheckReturnValue @NonNull default @NonNull Streamable<T> doOnNext(@NonNull @NonNull Consumer<? super @NonNull T> consumer) Calls the given consumer whenever an upstream item becomes available.- Parameters:
consumer- the callback to invoke with the next item from upstream- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifconsumerisnull
-
flatMap
@CheckReturnValue @NonNull default <R> @NonNull Streamable<R> flatMap(@NonNull @NonNull Function<? super @NonNull T, ? extends Streamable<? extends R>> mapper, @NonNull @NonNull StandardConcurrentConfig config) Maps each upstream item onto aStreamableand runs them concurrently while relaying inner items as first-come-first-served manner.- Type Parameters:
R- the element type of the output sequence- Parameters:
mapper- the function that turns an upstream item into aStreamableinner sequenceconfig- the configuration record for this operator- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifmapperorconfigisnull
-
groupBy
@CheckReturnValue @NonNull default <@Nullable K> @NonNull Streamable<GroupedStreamable<K,T>> groupBy(@NonNull @NonNull Function<? super @NonNull T, ? extends @Nullable K> keySelector) Maps each upstream item into aGroupedStreamablegroup, emits those groups and keeps relaying the upstream items into those groups.- Type Parameters:
K- the key type,nulls allowed- Parameters:
keySelector- the function that receives the upstream item and returns a key that determines which group the item will go into- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifkeySelectorisnull
-
hide
Hides the identity of thisStreamableand itsStreamer.Use it to break optimizations or hide concrete implementations.
- Returns:
- the new
Streamableinstance
-
ignoreElements
Ignores all elements from the currentStreamableand completes.- Returns:
- the new
Streamableinstance
-
intercept
@CheckReturnValue @NonNull default @NonNull Streamable<T> intercept(StreamableInterceptConfig<@NonNull T> config) Intercepts the lifecycle method calls ofStreamableandStreamerand allows the modification of them via Function callbacks.- Parameters:
config- the configuration record for this operator- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifconfigisnull
-
last
Signals the last item from the upstreamStreamableor the provideddefaultItemif the upstream is empty, as aSingleinstance.- Parameters:
defaultItem- the item to signal if the upstream turns out to be empty- Returns:
- the new
Singleinstance - Throws:
NullPointerException- ifdefaultItemisnull
-
lastOrError
Signals the last item from the upstreamStreamableor aNoSuchElementExceptionif the upstream is empty, as aSingleinstance.- Returns:
- the new
Singleinstance
-
lift
@CheckReturnValue @NonNull default <@NonNull R> @NonNull Streamable<R> lift(@NonNull @NonNull StreamableOperator<? super @NonNull T, ? extends @NonNull R> lifter) This method requires advanced knowledge about building operators, please consider other standard composition methods first; Returns aStreamableinstance which when itsstream(StreamerCancellation)is invoked, applies the specified operator callback to the upstreamStreamerto produce an actualStreamerinstance to be handed downstream.Use it to implement operators without creating the surrounding
Streamableclass.If the
lifterreturnsnullor throws, the downstream will receive a standard error streamer.- Type Parameters:
R- the downstream type of the sequence- Parameters:
lifter- the callback that will be invoked with the upstreamStreamerand is expected to produce aStreamerfor the downstream.- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- iflifterisnull
-
map
@CheckReturnValue @NonNull default <@NonNull R> @NonNull Streamable<R> map(@NonNull @NonNull Function<? super @NonNull T, ? extends @NonNull R> mapper) Maps each upstream item into another item via a mapper function.- Type Parameters:
R- the element type of the mapping- Parameters:
mapper- the function that takes an upstream item and returns an item to be emitted to the downstream- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifmapperisnull
-
mapOptional
@CheckReturnValue @NonNull default <@NonNull R> @NonNull Streamable<R> mapOptional(@NonNull @NonNull Function<? super @NonNull T, ? extends Optional<? extends @NonNull R>> mapper) Maps each upstream item into another, optional item via a mapper function that skips the empty optionals.- Type Parameters:
R- the element type of the mapping- Parameters:
mapper- the function that takes an upstream item and returns an optional item to be emitted / skipped to the downstream- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifmapperisnull
-
onErrorResumeNext
@CheckReturnValue @NonNull default @NonNull Streamable<T> onErrorResumeNext(@NonNull @NonNull Function<? super Throwable, ? extends Streamable<? extends @NonNull T>> fallbackMapper) When the upstream fails, the sequence is resumed by theStreamablethat is returned for the failureThrowable.- Parameters:
fallbackMapper- the function that receives the upstream error and should return aStreamableto resume the sequence with- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- iffallbackMapperisnull
-
repeat
Runs the upstream at most the givencounttimes while it succeeds.So a
repeat(1)will try to consume the upstream once.- Parameters:
count- the number of retries if the upstream fails- Returns:
- the new
Streamableinstance - Throws:
IllegalArgumentException- ifcountis negative
-
repeatWhen
@CheckReturnValue @NonNull default @NonNull Streamable<T> repeatWhen(Function<? super Long, ? extends CompletionStage<Boolean>> whenFunction) Repeats the upstream when the given function signalstruevia theCompletionStagefor the count how many times the upstream was streamed.The first repeat run will present 0 for the function.
- Parameters:
whenFunction- the function to call with the run index, it should signaltrueto repeat the source,falseto complete without error or complete exceptionally to become the failure result of the sequence.- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifwhenFunctionisnull
-
retry
Retries at most the givencounttimes the upstream if it fails with any error.So a
retry(1)will try to consume the upstream twice.- Parameters:
count- the number of retries if the upstream fails- Returns:
- the new
Streamableinstance - Throws:
IllegalArgumentException- ifcountis negative
-
retry
@CheckReturnValue @NonNull default @NonNull Streamable<T> retry(Predicate<? super Throwable> predicate) Retries the upstream if the given predicate returnstruefor the failureThrowableof the last streaming of the upstream.- Parameters:
predicate- the p- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifpredicateisnull
-
retry
@CheckReturnValue @NonNull default @NonNull Streamable<T> retry(BiPredicate<? super Long, ? super Throwable> predicate) Retries the upstream if the given predicate returnstruefor the failure count andThrowableof the last streaming of the upstream.The first failure run will present 0 for the predicate.
- Parameters:
predicate- the function to call with the failure index andThrowable- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifpredicateisnull
-
retryWhen
@CheckReturnValue @NonNull default @NonNull Streamable<T> retryWhen(BiFunction<? super Long, ? super Throwable, ? extends CompletionStage<Boolean>> whenFunction) Retries the upstream when the given predicate signalstruevia theCompletionStagefor the failure count andThrowableof the last streaming of the upstream.The first failure run will present 0 for the predicate.
- Parameters:
whenFunction- the function to call with the failure index andThrowable, it should signaltrueto retry the source,falseto complete without error or complete exceptionally to become the failure result of the sequence.- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifwhenFunctionisnull
-
skip
Skips the firstcountitems and relays the rest to the downstream.- Parameters:
count- the number of items to skip- Returns:
- the new
Streamableinstance - Throws:
IllegalArgumentException- ifcountis negative
-
take
Takes at most the given number of items from the upstream and relays it to the downstream, then cancels the rest of the sequence.Note that cancellation of the upstream happens when the downstream calls
Streamer.next()because unlike the push-basedtakeimplementations, the current upstream value has to remain accessible until the downstream callsnextorStreamer.finish().- Parameters:
count- the maximum number of items to relay- Returns:
- the new
Streamableinstance - Throws:
IllegalArgumentException- ifcountis negative
-
takeUntil
@CheckReturnValue @NonNull default <U> @NonNull Streamable<T> takeUntil(@NonNull @NonNull Streamable<U> other) Relays items from thisStreamableuntil the otherStreamablesignals an item or completes.- Type Parameters:
U- the element type of the otherStreamable- Parameters:
other- theStreamableexpected to signal when to stop taking items from thisStreamable- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifotherisnull
-
takeWhile
@CheckReturnValue @NonNull default @NonNull Streamable<T> takeWhile(@NonNull @NonNull Predicate<? super @NonNull T> predicate) Relays items from thisStreamablewhile the predicate returnstrue- Parameters:
predicate- the predicate to test if the sequence should keep going- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifpredicateisnull
-
timeout
@CheckReturnValue @NonNull default @NonNull Streamable<T> timeout(long timeout, @NonNull @NonNull TimeUnit unit, @NonNull @NonNull Scheduler scheduler, @NonNull @NonNull Streamable<@NonNull T> fallback) Applies a timeout to each upstream item and switches to the fallbackStreamableif the upstream doesn't produce an item within the given timeout period.- Parameters:
timeout- the time to wait for each upstream itemunit- the time unitscheduler- the scheduler where to wait for the next upstream itemfallback- theStreamableto switch to if the upstream doesn't produce an item within the time limit- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- ifunitorschedulerorfallbackisnull
-
to
@CheckReturnValue @NonNull default <@NonNull R> R to(@NonNull @NonNull StreamableConverter<@NonNull T, ? extends @NonNull R> converter) Calls the specified converter function during assembly time and returns its resulting value.This allows fluent conversion to any other type.
- Type Parameters:
R- the resulting object type- Parameters:
converter- the function that receives the currentObservableinstance and returns a value- Returns:
- the converted value
- Throws:
NullPointerException- ifconverterisnull
-
toFlowable
Converts the streamable into a Flowable representation, running on the default Executors.newVirtualThreadPerTaskExecutor() virtual thread.- Returns:
- the new Flowable instance
-
toFlowable
@CheckReturnValue @NonNull default @NonNull Flowable<T> toFlowable(@NonNull @NonNull ExecutorService executor) Converts thisStreamableinto aFlowablerepresentation, running on the provided executor service.- Parameters:
executor- the executor to use- Returns:
- the new
Flowableinstance - Throws:
NullPointerException- ifexecutorisnull
-
toObservable
Converts thisStreamableinto aObservablerepresentation, emitting items on whatever thread produces items in the currentStreamable.Unlike
toFlowable(ExecutorService), the lack of backpressure doesn't require any blocking thus any need to run the conversion on any particularSchedulerorExecutorServiceon its own.- Returns:
- the new
Observableinstance
-
transform
@CheckReturnValue @NonNull default <@NonNull R> @NonNull Streamable<R> transform(@NonNull @NonNull VirtualTransformer<@NonNull T, @NonNull R> transformer) Transforms the upstream sequence into zero or more elements for the downstream.- Type Parameters:
R- the result element type- Parameters:
transformer- the interface to implement the transforming logic- Returns:
- the new
Streamableinstance
-
transform
@CheckReturnValue @NonNull default <@NonNull R> @NonNull Streamable<R> transform(@NonNull @NonNull VirtualTransformer<@NonNull T, @NonNull R> transformer, @NonNull @NonNull ExecutorService executor) Transforms the upstream sequence into zero or more elements for the downstream.- Type Parameters:
R- the result element type- Parameters:
transformer- the interface to implement the transforming logicexecutor- where to run the transform and blocking operations- Returns:
- the new
Streamableinstance - Throws:
NullPointerException- iftransformerorexecutorisnull
-
forEach
@CheckReturnValue @NonNull default @NonNull CompletionStageDisposable<Void> forEach(@NonNull @NonNull Consumer<? super @NonNull T> consumer) Consumes elements from thisStreamablevia the provided executor service.- Parameters:
consumer- the callback that gets the elements until completion- Returns:
- a Disposable that lets one cancel the sequence asynchronously.
-
forEach
@CheckReturnValue @NonNull default @NonNull CompletionStageDisposable<Void> forEach(@NonNull @NonNull Consumer<? super @NonNull T> consumer, @NonNull @NonNull DisposableStreamerCancellation canceller) Consumes elements from thisStreamablevia the provided executor service.- Parameters:
consumer- the callback that gets the elements until completioncanceller- the container to trigger cancellation of the sequence- Returns:
- the
CompletionStagethat gets notified when the sequence ends
-
forEach
@CheckReturnValue @NonNull default @NonNull CompletionStageDisposable<Void> forEach(@NonNull @NonNull Consumer<? super @NonNull T> consumer, @NonNull @NonNull ExecutorService executor) Consumes elements from thisStreamablevia the provided executor service.- Parameters:
consumer- the callback that gets the elements until completionexecutor- the service that hosts the blocking waits.- Returns:
- a Disposable that lets one cancel the sequence asynchronously.
-
forEach
@CheckReturnValue @NonNull default @NonNull CompletionStageDisposable<Void> forEach(@NonNull @NonNull Consumer<? super @NonNull T> consumer, @NonNull @NonNull DisposableStreamerCancellation canceller, @NonNull @NonNull ExecutorService executor) Consumes elements from thisStreamablevia the provided executor service.- Parameters:
consumer- the callback that gets the elements until completioncanceller- the container to trigger cancellation of the sequenceexecutor- the service that hosts the blocking waits.- Returns:
- the new
CompletionStageDisposablethat gets notified when the sequence ends - Throws:
NullPointerException- ifconsumerorcancellerorexecutorisnull
-
forEach
@CheckReturnValue @NonNull default @NonNull CompletionStageDisposable<Void> forEach(@NonNull @NonNull BiConsumer<? super @NonNull T, ? super Disposable> consumer, @NonNull @NonNull DisposableStreamerCancellation canceller, @NonNull @NonNull ExecutorService executor) Consumes elements from thisStreamablevia the provided executor service.- Parameters:
consumer- the callback that gets the elements until completioncanceller- the container to trigger cancellation of the sequenceexecutor- the service that hosts the blocking waits.- Returns:
- the
CompletionStagethat gets notified when the sequence ends - Throws:
NullPointerException- ifconsumerorcancellerorexecutorisnull
-
subscribe
default void subscribe(@NonNull Flow.Subscriber<? super @NonNull T> subscriber, @NonNull @NonNull ExecutorService executor) Consume thisStreamablevia the given flow-reactive-streams subscriber.- Parameters:
subscriber- the subscriber to consume with.executor- the service that hosts the blocking waits.
-
subscribe
Consume thisStreamablevia the given flow-reactive-streams subscriber on a virtual thread backed executor service.- Parameters:
subscriber- the subscriber to consume with.
-
subscribe
@NonNull default @NonNull CompletionStage<Void> subscribe(@NonNull @NonNull StreamSink<? super @NonNull T> consumer) Relays the events of the upstream into aStreamSinkconsumer via the help of the standardExecutors.newVirtualThreadPerTaskExecutor()as a mediator for pull-to-push.- Parameters:
consumer- the consumer to relay events into- Returns:
- the stage that gets completed normally or with an exception when this
Streamableterminates - Throws:
NullPointerException- ifconsumerisnull
-
subscribe
@NonNull default @NonNull CompletionStage<Void> subscribe(@NonNull @NonNull StreamSink<? super @NonNull T> consumer, ExecutorService executor) Relays the events of the upstream into aStreamSinkconsumer via the help of the givenExecutorServiceas a mediator for pull-to-push.- Parameters:
consumer- the consumer to relay events intoexecutor- theExecutorServiceto run the blocking consume and emissions- Returns:
- the stage that gets completed normally or with an exception when this
Streamableterminates - Throws:
NullPointerException- ifconsumerorexecutorisnull
-
test
Creates a newTestSubscriberand subscribes it to thisStreamable.- Returns:
- the created test subscriber
-
test
@CheckReturnValue @NonNull default @NonNull TestSubscriber<T> test(@NonNull @NonNull ExecutorService executor) Creates a newTestSubscriberand subscribes it to thisStreamable.- Parameters:
executor- the executor to use- Returns:
- the created test subscriber
-