Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 36 ยท Reactive and Messaging

Mutiny: Uni and Multi

Learn Mutiny, the reactive library of Quarkus: Uni for one item, Multi for streams, map and flatMap, failure recovery, subscription and backpressure explained.

Quarkus can run in two styles. The imperative style is the Java you already know: a method runs, blocks while it waits for the database, and returns a value. The reactive style does not wait. It describes what should happen when data arrives, and a small number of event-loop threads move many requests forward. Mutiny is the library Quarkus uses for the second style.

Mutiny has only two types, which is its main selling point. A Uni<T> delivers one item or a failure; a Multi<T> delivers zero or more items, then completion or a failure. This lesson teaches both, the operators you will use daily, and the one rule that surprises everyone: nothing happens until someone subscribes.

Real Mutiny code is read-only here. The TryIts use CompletableFuture and the JDK's Flow API, which Mutiny is itself built on, to reproduce the behavior.

Uni: one result later

A REST endpoint that returns Uni<Book> says "I will have the book, but not yet":

Java
import io.smallrye.mutiny.Uni;

@GET
@Path("/{id}")
public Uni<Book> find(@PathParam("id") long id) {
    return repository.findById(id)                 // Uni<Book>
            .onItem().ifNull().failWith(() -> new NotFoundException("No book " + id))
            .onItem().transform(book -> book.withTitle(book.title().trim()));
}

Quarkus subscribes for you when it handles the HTTP call, and writes the response when the Uni completes. You never call block() in production code.

The operators read like a sentence. Pick an event type with onItem(), onFailure() or onCompletion(), then say what to do:

Goal Operator
Change the item onItem().transform(x -> ...)
Call another async step onItem().transformToUni(x -> otherUni(x))
Run a side effect onItem().invoke(x -> log(x))
Provide a fallback onFailure().recoverWithItem(defaultValue)
Retry onFailure().retry().atMost(3)
Time limit ifNoItem().after(Duration.ofSeconds(2)).fail()
Combine several Uni.combine().all().unis(a, b).asTuple()

Two names confuse beginners: transform is for a plain function (like map), and transformToUni is for a function that itself returns a Uni (like flatMap). If you use transform with an async call you end up with a Uni<Uni<X>>.

Java Stand-in: a Uni built on CompletableFuture

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the order of the output: the first line prints before the source runs. Building a pipeline is cheap and does no work. That laziness is what lets frameworks attach timeouts, retries and tracing before the first byte moves.

Multi: a stream of items

Multi<T> represents a stream. A REST endpoint returning Multi<String> can send Server-Sent Events; a Kafka consumer receives a Multi of messages:

Java
import io.smallrye.mutiny.Multi;
import java.time.Duration;

@GET
@Path("/ticks")
@Produces(MediaType.SERVER_SENT_EVENTS)
public Multi<String> ticks() {
    return Multi.createFrom().ticks().every(Duration.ofSeconds(1))
            .select().first(10)
            .onItem().transform(n -> "tick " + n);
}

Common operators:

Goal Operator
Transform each item onItem().transform(...)
Keep matching items select().where(x -> ...)
Take the first N select().first(n)
Drop duplicates select().distinct()
One async call per item onItem().transformToUniAndMerge(...) or ...AndConcatenate(...)
Gather into a list collect().asList() (gives a Uni<List<T>>)
Group group().intoLists().of(10)

Merge runs the inner calls at the same time and the order of results may differ; Concatenate runs them one after another and keeps the order. Choose deliberately.

Backpressure

A fast producer and a slow consumer need a way to talk to each other, or memory fills up. Reactive Streams solve this with demand: the subscriber says request(n), and the publisher sends at most n items. Mutiny follows the same rule. By default a Quarkus endpoint requests as much as it can handle, and operators like onOverflow().buffer(100) or .drop() say what to do when a source pushes faster than the demand.

Java Stand-in: demand-driven streaming with Flow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The publisher never sends an item the subscriber did not ask for. That is the whole idea of backpressure.

Subscribing, and where code runs

Three things to carry into real projects:

  1. Nothing runs without a subscription. If you call repository.persist(book) and drop the returned Uni, the insert never happens. Return it from your method, or subscribe.
  2. Do not block on an event-loop thread. uni.await().indefinitely() is allowed on worker threads and in tests, and forbidden inside reactive code that runs on an I/O thread: Quarkus throws an exception to protect you. See event loop and blocking code.
  3. Failures travel as events. A thrown exception inside transform becomes a failure signal. Handle it with onFailure(), and do not use try/catch around an operator chain.

The classic bug is a Uni that is created and ignored. Because it is lazy, the code compiles, runs and silently does nothing.

Converting between styles

Mutiny converts to and from other libraries and to the JDK: uni.subscribeAsCompletionStage(), Uni.createFrom().completionStage(cf), Multi.createFrom().iterable(list), and, with the right extension, RxJava or Reactor types. In an imperative method you may call uni.await().atMost(Duration.ofSeconds(5)).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between Uni<T> and Multi<T>?

    Uni models a single asynchronous result, Multi a stream of results.
  2. 2. What happens if you create a Uni and never subscribe or return it?

    Work starts at subscription. Returning the Uni from an endpoint lets Quarkus subscribe for you.
  3. 3. Which operator should you use when the mapping function itself returns a Uni?

    transformToUni flattens the inner Uni. Using transform would produce a nested Uni<Uni<X>>.
  4. 4. What does backpressure mean?

    The subscriber requests n items; the publisher must not send more than that.

Summary

  • Uni<T> is one future item or failure; Multi<T> is a stream.
  • Operators are grouped by event: onItem(), onFailure(), onCompletion().
  • Pipelines are lazy: nothing happens until subscription; return the Uni so Quarkus subscribes.
  • Backpressure lets a subscriber control the rate with request(n).
  • Never block an I/O thread waiting for a Uni.

Next: The Event Loop and Blocking Code