What is the switchIfEmpty alternative in Smallrye Mutiny

2.7k views Asked by At

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?

1

There are 1 answers

4
Clement On

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

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