Home > Mobile >  How to rewrite Uni<List<Fruit>> to Multi without a list? Reactive Programming
How to rewrite Uni<List<Fruit>> to Multi without a list? Reactive Programming

Time:11-25

As i am working in a Project where i want to rewrite the Uni to Multi for a method "findall" to get all the mongodb Document from a collection. I tried to rewrite but not able to find a solution

original:

public Uni<List<Book>> findAll(List<String> authors)
    {

        return getCollection().
                find(Filters.all("authors",authors)).map(Book::from).collectItems().asList();
}

What i tried (But not working)

public Multi<Book> findAll(List<String> authors)

        {
    return getCollection().find(Filters.all("authors",authors)).transform().
                    byFilteringItemsWith(Objects::nonNull).onCompletion().ifEmpty().
                    failWith(new NoSuchElementException("couldn't find the Authors")).onItem().transform(Book::from);
    }

CodePudding user response:

I suppose you are using the ReactiveMongoClient provided by Quarkus. In this case, your method should be:

ReactiveMongoClient client;

public ReactiveMongoCollection<Book> getCollection() {
    return client.getDatabase("db").getCollection("books", Book.class);
}

public Multi<Book> findAll(List<String> authors) {
    return getCollection()
            .find(Filters.all("authors",authors))
            .onItem().transform(Book::from)
            .onCompletion().ifEmpty()
                 .failWith(new NoSuchElementException("..."));

}

You don't need to do thebyFilteringItemsWith, as a Multi cannot contain null items.

  • Related