Skip to content

How to handle null?#

The Uni type can emit null as item.

While there are mixed feelings about null, it’s part of the Java language and so handled in the Uni type.

Important

Multi does not support null items as it would break the compatibility with the Reactive Streams protocol.

Emitting null is convenient when returning Uni<Void>. However, the downstream must expect null as item.

Thus, Uni provides specific methods to handle null item. uni.onItem().ifNull() lets you decide what you want to do when the received item is null:

1
2
3
uni.onItem().ifNull().continueWith("hello");
uni.onItem().ifNull().switchTo(() -> Uni.createFrom().item("hello"));
uni.onItem().ifNull().failWith(() -> new Exception("Boom!"));

A symmetric group of methods is also available with ifNotNull which let you handle the case where the item is not null:

1
2
3
uni
    .onItem().ifNotNull().transform(String::toUpperCase)
    .onItem().ifNull().continueWith("yolo!");

Important

While supported, emitting null should be avoided except for Uni<Void>.