'Apply complex business logic to Multi object and return a Uni object in Rest API

Inside a rest function I'm making a reactive Postgres Db call which is returning a Multi. My intention is to run a complex business logic on Multi and return a new Uni.

@GET
public Uni<Object2> get() {
    Multi<Object1> objects = DB.getAll(dbClient);

    Uni<HashMap<String, FileTreeNode>> response; // Not sure how to initialize this object without any value
    List<Object1> result = new ArrayList<>();
    objects.subscribe().with(
    object -> result.add(object),
    failure -> System.out.println("Failed with " + failure),
    () -> {
        // Update Uni response object here.
    });

    return response;

}

Can anyone point me how to create the Uni object and mark it complete inside the business logic so that downstream services notified.



Solution 1:[1]

I have already answered on the Mutiny GitHub project. You need to collect your items into the Map using:

Uni<Map<String, String>> uni =
        multi.collect()
                .asMap(item -> getUniqueKeyForItem(item));

If you need more complex logic, you can provide your own accumulator:

Uni<MyCollection> uni = multi.collect()
        .in(MyCollection::new, (col, item) -> col.add(item));

See https://smallrye.io/smallrye-mutiny/guides/collecting-items for more details.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Clement