What is the switchIfEmpty alternative in Smallrye Mutiny
Asked Answered
F

1

5

In RxJava 2 and Reactor there is a switchIfEmptylike method to switch to new flow if there is no elements in current flow.

But when I began to use Minuty, I can not find an alternative when I convert my Quarkus sample to use the Reactive features.

Currently my solution is: in my PostRepository, I use an exception to indicate there is no post found.

 public Uni<Post> findById(UUID id) {
        return this.client
                .preparedQuery("SELECT * FROM posts WHERE id=$1", Tuple.of(id))
                .map(RowSet::iterator)
                .flatMap(it -> it.hasNext() ? Uni.createFrom().item(rowToPost(it.next())) : Uni.createFrom().failure(()-> new PostNotFoundException()));
    }

And catch it in the PostResource.

@Path("{id}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Uni<Response> getPostById(@PathParam("id") final String id) {
        return this.posts.findById(UUID.fromString(id))
                .map(data -> ok(data).build())
                .onFailure(PostNotFoundException.class).recoverWithItem(status(Status.NOT_FOUND).build());
    }

How to return an Uni means 0 or 1 element in PostRepository, and use a switchIfEmpty like method in PostResource to build the alternative path for the flow?

Ferrara answered 10/4, 2020 at 13:4 Comment(0)
C
6

Uni cannot be empty in the sense it always contains an item (potentially null).

So, the equivalent of switchIfEmpty is uni.onItem().ifNull().switchTo(() -> ...)

Caudal answered 23/4, 2020 at 13:29 Comment(6)
It does not work as switchIfEmpty in the stream if there is null.The null is still passed to the main flow, eg map(null will go here instead).onItem().ifNull....Ferrara
Yes, because null is a valid item as it's part of the Java language. We have added ifNonNull in Mutiny 0.5.0.Caudal
Mutiny 2.5.6 has an Uni.creatyFrom().nothing(); is that an empty Uni? In project-reactor Mono couldn't have a null, but it could be empty, in Mutiny we should use a Uni with null item as the empty Uni? And use the above way to check it? Why a Uni can't be empty? It feel intuitive i think to be allowed to be empty. Also Uni doesn't have a onComplete which confuses me, but i guess its the same as onItem.Cassandra
There is a distinction between a Uni never emitting an item or a failure, and an Uni emitting null. Mono.empty would be equivalent to a Uni emitting null.Caudal
@Caudal Mono does not accept null, Mono.empty does not emit any element, just sends a terminal signal. But Uni accepts null as elements.Ferrara
@Hantsy, Yes, I know. Emitting null in an Uni makes it complete (with null), which means you can use the ifNull().switchTo()....Caudal

© 2022 - 2024 — McMap. All rights reserved.