Transforming items

Learn how to (synchronously) transform received item

Both Unis and Multis emit items. One of the most common operations you will do is transforming these items using a synchronous 1-to-1 function.

To achieve this, you use onItem().transform(Function<T, U>). It calls the passed function for each item and produces the result as an item which is propagaed downstream.

Transforming items synchronously

Transforming items produced by a Uni

Let’s imagine you have a Uni<String>, and you want to capitalize the received String. Implementing this transformation is done as follows:

Uni<String> uni = Uni.createFrom().item("hello");
uni
        .onItem().transform(i -> i.toUpperCase())
        .subscribe().with(
        item -> System.out.println(item)); // Print HELLO

Transforming items produced by a Multi

The only difference for Multi is that the function is called for each item:

Multi<String> m = multi
        .onItem().transform(i -> i.toUpperCase());

The produced items are passed to the downstream subscriber:

Multi<String> multi = Multi.createFrom().items("a", "b", "c");
multi
        .onItem().transform(i -> i.toUpperCase())
        .subscribe().with(
            item -> System.out.println(item)); // Print A B C

What if the transformation failed?

If the transformation throws an exception, that exception is caught and passed to the downstream subscriber as a failure event. It also means that the subscriber won’t get further item after that failure.

Chaining multiple transformations

You can chain multiple transformations:

Uni<String> u = uni
        .onItem().transform(i -> i.toUpperCase())
        .onItem().transform(i -> i + "!");