Interface Uni<T>
-
- Type Parameters:
T- the type of item produced by theUni
- All Known Implementing Classes:
AbstractUni,UniAndCombination,UniCreateFromCompletionStage,UniCreateFromCompletionStageWithState,UniCreateFromDeferredSupplier,UniCreateFromDeferredSupplierWithState,UniCreateFromEmitterWithState,UniCreateFromFailureSupplier,UniCreateFromFuture,UniCreateFromItemSupplier,UniCreateFromItemWithState,UniCreateFromKnownFailure,UniCreateFromKnownItem,UniCreateFromPublisher,UniCreateWithEmitter,UniDelayOnItem,UniDelayUntil,UniEmitOn,UniFailOnTimeout,UniGlobalSpy,UniLogger,UniMemoizeOp,UniNever,UniOnCancellation,UniOnCancellationCall,UniOnCancellationSpy,UniOnFailureFlatMap,UniOnFailureSpy,UniOnFailureTransform,UniOnItemConsume,UniOnItemOrFailureConsume,UniOnItemOrFailureFlatMap,UniOnItemOrFailureMap,UniOnItemOrFailureSpy,UniOnItemSpy,UniOnItemTransform,UniOnItemTransformToUni,UniOnSubscribeCall,UniOnSubscribeInvoke,UniOnSubscribeSpy,UniOnTermination,UniOnTerminationCall,UniOnTerminationSpy,UniOperator,UniOrCombination,UniRetryAtMost,UniRunSubscribeOn
public interface Uni<T>AUnirepresents a lazy asynchronous action. It follows the subscription pattern, meaning that the action is only triggered once aUniSubscribersubscribes to theUni.A
Unican have two outcomes:- An
itemevent, forwarding the completion of the action (potentiallynullif the item does not represent a value, but the action was completed successfully) - A
failureevent, forwarding an exception
To trigger the computation, a
UniSubscribermust subscribe to the Uni. It will be notified of the outcome once there is anitemorfailureevent fired by the observed Uni. A subscriber receives (asynchronously) aUniSubscriptionand can cancel the demand at any time. Note that cancelling after having received the outcome is a no-op.
-
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Default Methods Deprecated Methods Modifier and Type Method Description UniAwait<T>await()Awaits (blocking the caller thread) until the item or a failure is emitted by the observedUni.default Uni<T>cache()Deprecated.UseUniMemoize.indefinitely()insteaddefault Uni<T>call(java.util.function.Function<? super T,Uni<?>> function)Produces a newUniinvoking the given @{code action} when theitemevent is received.default Uni<T>call(java.util.function.Supplier<Uni<?>> supplier)Produces a newUniinvoking the given @{code action} when theitemevent is received, but ignoring it.default <O> Uni<O>chain(java.util.function.Function<? super T,Uni<? extends O>> mapper)Once the observedUniemits an item, execute the givenmapper.default <O> Uni<O>chain(java.util.function.Supplier<Uni<? extends O>> supplier)Once the observedUniemits an item, execute the givensupplier.static UniCombinecombine()UniConvert<T>convert()Converts anUnito other types such asCompletionStagestatic UniCreatecreateFrom()Creates a newUnifrom various sources such asCompletionStage,UniEmitter, direct values,Exception...Uni<T>emitOn(java.util.concurrent.Executor executor)Produces a newUniinvoking theUniSubscriber.onItem(Object)andUniSubscriber.onFailure(Throwable)on the suppliedExecutor.default Uni<T>eventually(java.lang.Runnable action)Execute an action after an item or a failure has been emitted.default <O> Uni<T>eventually(java.util.function.Supplier<Uni<? extends O>> supplier)default <O> Uni<O>flatMap(java.util.function.Function<? super T,Uni<? extends O>> mapper)Transforms the received item asynchronously, forwarding the events emitted by anotherUniproduced by the givenmapper.UniIfNoItem<T>ifNoItem()Produces aUnireacting when a no item event is fired by the upstream uni during the specified time period.default Uni<T>invoke(java.lang.Runnable callback)Produces a newUniinvoking the given callback when theitemevent is fired, but ignoring it.default Uni<T>invoke(java.util.function.Consumer<? super T> callback)Produces a newUniinvoking the given callback when theitemevent is fired.Uni<T>log()Log events (onSubscribe, onItem, ...) as they come from the upstream or the subscriber, and derives the identifier from the upstream operator class "simple name".Uni<T>log(java.lang.String identifier)Log events (onSubscribe, onItem, ...) as they come from the upstream or the subscriber.default <O> Uni<O>map(java.util.function.Function<? super T,? extends O> mapper)Transforms the item (potentially null) emitted by thisUniby applying a (synchronous) function to it.UniMemoize<T>memoize()Configure memoization of theUniitem or failure.UniOnCancel<T>onCancellation()Configures actions to be performed when the subscriber cancels the subscription.UniOnFailure<T>onFailure()LikeonFailure(Predicate)but applied to all failures fired by the upstream uni.UniOnFailure<T>onFailure(java.lang.Class<? extends java.lang.Throwable> typeOfFailure)Configures a type of failure filtering the failures on which the behavior (specified with the returnedUniOnFailure) is applied.UniOnFailure<T>onFailure(java.util.function.Predicate<? super java.lang.Throwable> predicate)Configures a predicate filtering the failures on which the behavior (specified with the returnedUniOnFailure) is applied.UniOnItem<T>onItem()Configures the action to execute when the observedUniemits the item (potentiallynull).UniOnItemOrFailure<T>onItemOrFailure()Configures the action to execute when the observedUniemits either an item (potentiallynull)) or a failure.UniOnSubscribe<T>onSubscribe()Configures the action to execute when the observedUnisends aUniSubscription.UniOnTerminate<T>onTermination()Configures actions to be performed on termination, that is, on item, on failure, or when the subscriber cancels the subscription.default <R> Uni<R>plug(java.util.function.Function<Uni<T>,Uni<R>> operatorProvider)Plug a user-defined operator that does not belong to the existing Mutiny API.UniRepeat<T>repeat()Allows configuring repeating behavior.default <O> Uni<O>replaceWith(Uni<O> uni)default <O> Uni<O>replaceWith(java.util.function.Supplier<O> supplier)Ignore the item emitted by thisUniand replace it with another value using aSupplier.default <O> Uni<O>replaceWith(O item)Ignore the item emitted by thisUniand replace it with another value.default Uni<T>replaceWithNull()Ignore the item emitted by thisUniand replace it withnull.default Uni<java.lang.Void>replaceWithVoid()Uni<T>runSubscriptionOn(java.util.concurrent.Executor executor)default <O> Ostage(java.util.function.Function<Uni<T>,O> stage)Allows structuring the pipeline by creating a logic separation:UniSubscribe<T>subscribe()Requests theUnito start resolving the item and allows configuring how the signals are propagated (using aUniSubscriber, callbacks, or aCompletionStage.default java.util.concurrent.CompletableFuture<T>subscribeAsCompletionStage()Shortcut forUniSubscribe.asCompletionStage().Multi<T>toMulti()
-
-
-
Method Detail
-
createFrom
static UniCreate createFrom()
Creates a newUnifrom various sources such asCompletionStage,UniEmitter, direct values,Exception...Examples:
Uni.createFrom().item(1); // Emit 1 at subscription time Uni.createFrom().item(() -> x); // Emit x at subscription time, the supplier is invoked for each subscription Uni.createFrom().completionStage(cs); // Emit the item from this completion stage Uni.createFrom().completionStage(() -> cs); // Emit the item from this completion stage, the stage is not created before subscription Uni.createFrom().failure(exception); // Emit the failure at subscription time Uni.createFrom().deferred(() -> Uni.from().value(x)); // Defer the uni creation until subscription. Each subscription can produce a different uni Uni.createFrom().item(null); // Emit null at subscription time Uni.createFrom().nothing(); // Create a Uni not emitting any signal Uni.createFrom().publisher(publisher); // Create a Uni from a Reactive Streams Publisher
-
stage
default <O> O stage(java.util.function.Function<Uni<T>,O> stage)
Allows structuring the pipeline by creating a logic separation:Uni uni = upstream .stage(u -> { ...}) .stage(u -> { ...}) .stage(u -> { ...})With `stage` you can structure and chain groups of processing.
-
combine
static UniCombine combine()
- Returns:
- the factory use to combine the uni instances
-
subscribe
UniSubscribe<T> subscribe()
Requests theUnito start resolving the item and allows configuring how the signals are propagated (using aUniSubscriber, callbacks, or aCompletionStage. Unlikeawait(), this method configures non-blocking retrieval of the item and failure.Examples:
Uni<String> uni = ...; Subscription sub = uni.subscribe().with( // The return subscription can be used to cancel the operation item -> {}, // Callback calls on item failure -> {} // Callback calls on failure ); UniSubscriber<String> myUniSubscriber = ... uni.subscribe().withSubscriber(myUniSubscriber); // Subscribes to the Uni with the passed subscriber CompletableFuture future = uni.subscribe().asCompletableFuture(); // Get a CompletionStage receiving the item or failure // Cancelling the returned future cancels the subscription.- Returns:
- the object to configure the subscription.
- See Also:
uni.await() for waiting (blocking the caller thread) until the resolution of the observed Uni.
-
subscribeAsCompletionStage
default java.util.concurrent.CompletableFuture<T> subscribeAsCompletionStage()
Shortcut forUniSubscribe.asCompletionStage().- Returns:
- the completion stage receiving the items emitted by this
Uni
-
await
UniAwait<T> await()
Awaits (blocking the caller thread) until the item or a failure is emitted by the observedUni. If the observed uni fails, the failure is thrown. In the case of a checked exception, the exception is wrapped into aCompletionException.Examples:
Uni<T> uni = ...; T res = uni.await().indefinitely(); // Await indefinitely until it get the item. T res = uni.await().atMost(Duration.ofMillis(1000)); // Awaits at most 1s. After that, a TimeoutException is thrown Optional<T> res = uni.await().asOptional().indefinitely(); // Retrieves the item as an Optional, empty if the item is null- Returns:
- the object to configure the retrieval.
-
onItem
UniOnItem<T> onItem()
Configures the action to execute when the observedUniemits the item (potentiallynull).Examples:
Uni<T> uni = ...; uni.onItem().transform(x -> ...); // Transform the item into another item (~ map) uni.onItem().transformToUni(x -> ...); // Transform the item into a Uni (~ flatMap)- Returns:
- the object to configure the action to execute when an item is emitted
-
onSubscribe
UniOnSubscribe<T> onSubscribe()
Configures the action to execute when the observedUnisends aUniSubscription. The downstream don't have a subscription yet. It will be passed once the configured action completes.Example:
uni.onSubscribe().invoke(sub -> System.out.println("subscribed")); // Delay the subscription by 1 second (or until an asynchronous action completes) uni.onSubscribe().call(sub -> Uni.createFrom(1).onItem().delayIt().by(Duration.ofSecond(1)));- Returns:
- the object to configure the action to execution on subscription.
-
onItemOrFailure
UniOnItemOrFailure<T> onItemOrFailure()
Configures the action to execute when the observedUniemits either an item (potentiallynull)) or a failure. UnlikeonItem()andonFailure()the action would handle both cases in on "go".- Returns:
- the object to configure the action to execute when an item is emitted or when a failure is propagated.
-
onFailure
UniOnFailure<T> onFailure()
LikeonFailure(Predicate)but applied to all failures fired by the upstream uni. It allows configuring the on failure behavior (recovery, retry...).- Returns:
- a UniOnFailure on which you can specify the on failure action
-
onFailure
UniOnFailure<T> onFailure(java.util.function.Predicate<? super java.lang.Throwable> predicate)
Configures a predicate filtering the failures on which the behavior (specified with the returnedUniOnFailure) is applied.For instance, to only when an
IOExceptionis fired as failure you can use:uni.onFailure(IOException.class).recoverWithItem("hello")The fallback value (
hello) will only be used if the upstream uni fire a failure of typeIOException.- Parameters:
predicate- the predicate,nullmeans applied to all failures- Returns:
- a UniOnFailure configured with the given predicate on which you can specify the on failure action
-
onFailure
UniOnFailure<T> onFailure(java.lang.Class<? extends java.lang.Throwable> typeOfFailure)
Configures a type of failure filtering the failures on which the behavior (specified with the returnedUniOnFailure) is applied.For instance, to only when an
IOExceptionis fired as failure you can use:uni.onFailure(IOException.class).recoverWithItem("hello")The fallback value (
hello) will only be used if the upstream uni fire a failure of typeIOException.- Parameters:
typeOfFailure- the class of exception, must not benull- Returns:
- a UniOnFailure configured with the given predicate on which you can specify the on failure action
-
ifNoItem
UniIfNoItem<T> ifNoItem()
Produces aUnireacting when a no item event is fired by the upstream uni during the specified time period.This
Unidetects if thisUnidoes not emit an item before the configured timeout.Examples:
uni.ifNoItem().after(Duration.ofMillis(1000).fail() // Propagate a TimeOutException uni.ifNoItem().after(Duration.ofMillis(1000).recoverWithValue("fallback") // Inject a fallback item on timeout uni.ifNoItem().after(Duration.ofMillis(1000).on(myExecutor)... // Configure the executor calling on timeout actions uni.ifNoItem().after(Duration.ofMillis(1000).retry().atMost(5) // Retry five times- Returns:
- the on timeout group
-
emitOn
Uni<T> emitOn(java.util.concurrent.Executor executor)
Produces a newUniinvoking theUniSubscriber.onItem(Object)andUniSubscriber.onFailure(Throwable)on the suppliedExecutor.Instead of receiving the
itemevent on the thread firing the event, this method influences the threading context to switch to a thread from the given executor.- Parameters:
executor- the executor to use, must not benull- Returns:
- a new
Uni
-
runSubscriptionOn
Uni<T> runSubscriptionOn(java.util.concurrent.Executor executor)
When a subscriber subscribes to thisUni, executes the subscription to the upstreamUnion a thread from the given executor. As a result, theUniSubscriber.onSubscribe(UniSubscription)method will be called on this thread (except mentioned otherwise)- Parameters:
executor- the executor to use, must not benull- Returns:
- a new
Uni
-
memoize
@Experimental("Memoization is an experimental feature at this stage") UniMemoize<T> memoize()Configure memoization of theUniitem or failure.- API Note:
- This is an experimental API
- Returns:
- the object to configure memoization
-
cache
@Deprecated default Uni<T> cache()
Deprecated.UseUniMemoize.indefinitely()insteadCaches the events (item or failure) of thisUniand replays it for all furtherUniSubscriber.
-
map
default <O> Uni<O> map(java.util.function.Function<? super T,? extends O> mapper)
Transforms the item (potentially null) emitted by thisUniby applying a (synchronous) function to it. This method is equivalent touni.onItem().apply(x -> ...)For asynchronous composition, look at flatMap.- Type Parameters:
O- the output type- Parameters:
mapper- the mapper function, must not benull- Returns:
- a new
Unicomputing an item of type<O>.
-
invoke
default Uni<T> invoke(java.util.function.Consumer<? super T> callback)
Produces a newUniinvoking the given callback when theitemevent is fired. Note that the item can benull.If the callback throws an exception, this exception is propagated to the downstream as failure.
This method is a shortcut on
UniOnItem.invoke(Consumer)- Parameters:
callback- the callback, must not benull- Returns:
- the new
Uni
-
invoke
default Uni<T> invoke(java.lang.Runnable callback)
Produces a newUniinvoking the given callback when theitemevent is fired, but ignoring it.If the callback throws an exception, this exception is propagated to the downstream as failure.
This method is a shortcut on
UniOnItem.invoke(Consumer)- Parameters:
callback- the callback, must not benull- Returns:
- the new
Uni
-
call
default Uni<T> call(java.util.function.Function<? super T,Uni<?>> function)
Produces a newUniinvoking the given @{code action} when theitemevent is received. Note that the received item can benull.Unlike
invoke(Consumer), the passed function returns aUni. When the producedUnisends its item, this item is discarded, and the originalitemis forwarded downstream. If the producedUnifails, the failure is propagated downstream. If the callback throws an exception, this exception is propagated downstream as failure.This method is a shortcut on
UniOnItem.call(Function)
-
call
default Uni<T> call(java.util.function.Supplier<Uni<?>> supplier)
Produces a newUniinvoking the given @{code action} when theitemevent is received, but ignoring it.Unlike
invoke(Consumer), the passed function returns aUni. When the producedUnisends its item, this item is discarded, and the originalitemis forwarded downstream. If the producedUnifails, the failure is propagated downstream. If the callback throws an exception, this exception is propagated downstream as failure.This method is a shortcut on
UniOnItem.call(Function)
-
flatMap
default <O> Uni<O> flatMap(java.util.function.Function<? super T,Uni<? extends O>> mapper)
Transforms the received item asynchronously, forwarding the events emitted by anotherUniproduced by the givenmapper.The mapper is called with the item event of the current
Uniand produces anUni, possibly using another type of item (R). The events fired by producedUniare forwarded to theUnireturned by this method.This operation is generally named
flatMap. This method is a shortcut onUniOnItem.transformToUni(Function)onItem().transformToUni(mapper)}.
-
chain
default <O> Uni<O> chain(java.util.function.Function<? super T,Uni<? extends O>> mapper)
Once the observedUniemits an item, execute the givenmapper. This mapper produces anotherUni. The downstream receives the events emitted by this producedUni. This operation allows chaining asynchronous operations: when the upstream completes with an item, run the mapper and emits the item (or failure) sent by the producedUni:Uni<Session> uni = getSomeSession(); return uni.chain(session -> session.persist(fruit)) .chain(session -> session.flush()) .map(x -> Response.ok(fruit).status(201).build());The mapper is called with the item event of the currentUniand produces anUni, possibly using another type of item (O). The events fired by producedUniare forwarded to theUnireturned by this method.This operation is generally named
flatMap. This method is a shortcut foronItem().transformToUni(mapper).- Type Parameters:
O- the type of item- Parameters:
mapper- the function called with the item of thisUniand producing theUni, must not benull, must not returnnull.- Returns:
- a new
Unithat would fire events from the uni produced by the mapper function, possibly in an asynchronous manner. - See Also:
chain(Supplier)
-
chain
default <O> Uni<O> chain(java.util.function.Supplier<Uni<? extends O>> supplier)
Once the observedUniemits an item, execute the givensupplier. This supplier produces anotherUni. The downstream receives the events emitted by this producedUni. This operation allows chaining asynchronous operations: when the upstream completes with an item, run the supplier and emits the item (or failure) sent by the producedUni:Uni<Session> uni = getSomeSession(); return uni.chain(session -> session.persist(fruit)) .chain(session -> session.flush()) .chain(() -> server.close());The supplier ignores the item event of the currentUniand produces anUni, possibly using another type of item (O). The events fired by producedUniare forwarded to theUnireturned by this method.This method is a shortcut for
UniOnItem.transformToUni(Function)onItem().transformToUni(ignored -> supplier.get()).- Type Parameters:
O- the type of item- Parameters:
supplier- the supplier producing theUni, must not benull, must not returnnull.- Returns:
- a new
Unithat would fire events from the uni produced by the mapper function, possibly in an asynchronous manner. - See Also:
chain(Supplier)
-
eventually
default Uni<T> eventually(java.lang.Runnable action)
Execute an action after an item or a failure has been emitted. This is equivalent to afinallyblock in Java.String id = ...; Session session = getSomeSession(); session.find(Fruit.class, id) .chain(fruit -> session.remove(fruit) .then(() -> session.flush()) .eventually(() -> session.close());This method is a shortcut for
UniOnItemOrFailure.invoke(BiConsumer):onItemOrFailure().invoke((item, err) -> action.run())- Parameters:
action- an action to perform, must not benull.- Returns:
- a new
Unithat emits events once the action has completed. - See Also:
onItemOrFailure()
-
eventually
default <O> Uni<T> eventually(java.util.function.Supplier<Uni<? extends O>> supplier)
When thisUniemits an item or a failure, invoke aUnisupplier then invoke the suppliedUni. When the suppliedUniemits an item then it is ignored, and when it emits a failure it is reported.This is equivalent to a
finallyblock in Java.String id = ...; Session session = getSomeSession(); session.find(Fruit.class, id) .chain(fruit -> session.remove(fruit) .eventually(() -> session.close());This method is a shortcut for
UniOnItemOrFailure.call(BiFunction):onItemOrFailure().call((item, err) -> supplier.get())- Type Parameters:
O- the type of the item- Parameters:
supplier- aUnisupplier, cannot benulland cannot returnnull.- Returns:
- a new
Unithat emits events once the suppliedUniemits an item or a failure. - See Also:
onItemOrFailure()
-
convert
UniConvert<T> convert()
Converts anUnito other types such asCompletionStageExamples:
uni.convert().toCompletionStage(); // Convert to CompletionStage using convenience method uni.convert().with(BuiltinConverters.toCompletionStage()); // Convert to CompletionStage using BuiltInConverters uni.convert().with(uni -> x); // Convert with a custom lambda converter- Returns:
- the object to convert an
Uniinstance - See Also:
UniConvert
-
toMulti
Multi<T> toMulti()
Creates an instance ofMultifrom thisUni.When a subscriber subscribes to the returned
Multiand request an item, it subscribes to thisUniand the events from thisUniare propagated to theMulti:- if this
Uniemits a non-nullitem - this item is propagated to theMultiand followed with the completion event - if this
Uniemits anullitem - theMultifires the completion event - if this
Uniemits a failure, this failure event is propagated by theMulti
It's important to note that the subscription to this
Unihappens when the subscriber to the producedMultirequests items, and not at subscription time.- Returns:
- the produced
Multi, nevernull
- if this
-
repeat
UniRepeat<T> repeat()
Allows configuring repeating behavior. Repeating allow transforming aUniinto aMultieither a specific amount of times or indefinitely. Each time, a new subscription is attempted on theUni. Cancelling the subscription stops the repeating behavior.- Returns:
- the object to configure the repeating behavior.
-
onTermination
UniOnTerminate<T> onTermination()
Configures actions to be performed on termination, that is, on item, on failure, or when the subscriber cancels the subscription.- Returns:
- the object to configure the termination actions.
-
onCancellation
UniOnCancel<T> onCancellation()
Configures actions to be performed when the subscriber cancels the subscription.- Returns:
- the object to configure the cancellation actions.
-
plug
default <R> Uni<R> plug(java.util.function.Function<Uni<T>,Uni<R>> operatorProvider)
Plug a user-defined operator that does not belong to the existing Mutiny API.
-
replaceWith
default <O> Uni<O> replaceWith(O item)
Ignore the item emitted by thisUniand replace it with another value.This is a shortcut for
uni.onItem().transform(ignore -> item).- Type Parameters:
O- the output type- Parameters:
item- the replacement value- Returns:
- the new
Uni
-
replaceWith
default <O> Uni<O> replaceWith(java.util.function.Supplier<O> supplier)
Ignore the item emitted by thisUniand replace it with another value using aSupplier.This is a shortcut for
uni.onItem().transform(ignore -> supplier.get()).- Type Parameters:
O- the output type- Parameters:
supplier- the replacement value supplier- Returns:
- the new
Uni
-
replaceWithNull
default Uni<T> replaceWithNull()
Ignore the item emitted by thisUniand replace it withnull.This is a shortcut for
uni.onItem().transform(ignore -> null).- Returns:
- the new
Uni
-
replaceWithVoid
default Uni<java.lang.Void> replaceWithVoid()
Ignore the item emitted by thisUniand replace it withnulland typeVoid.This method is in effect similar to
replaceWithNull(), except that it returns aUni<Void>instead of aUni<T>.This is a shortcut for
uni.onItem().transform(ignored -> null).- Returns:
- the new
Uni
-
log
Uni<T> log(java.lang.String identifier)
Log events (onSubscribe, onItem, ...) as they come from the upstream or the subscriber. Events will be logged as long as theUnihasn't been cancelled or terminated. Logging is framework-agnostic and can be configured in theInfrastructureclass.- Parameters:
identifier- an identifier of this operator to be used in log events- Returns:
- a new
Uni - See Also:
Infrastructure.setOperatorLogger(Infrastructure.OperatorLogger)
-
log
Uni<T> log()
Log events (onSubscribe, onItem, ...) as they come from the upstream or the subscriber, and derives the identifier from the upstream operator class "simple name". Events will be logged as long as theUnihasn't been cancelled or terminated. Logging is framework-agnostic and can be configured in theInfrastructureclass.- Returns:
- a new
Uni - See Also:
log(String),Infrastructure.setOperatorLogger(Infrastructure.OperatorLogger)
-
-