1

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.

Abhijeet
  • 35
  • 5

1 Answers1

2

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.

Clement
  • 2,817
  • 1
  • 12
  • 11
  • Thanks Clement for responding here too. Looks like I was not clear about my question. I don't want to apply business logic on the item and store the mutated value in the map. My requirement is first to collect all elements from the Multi object and when all elements are received apply the business logic at the end (this is important). When I apply this business logic this generates a HashMap which I need to convert to Uni object. – Abhijeet May 21 '22 at 02:21
  • 1
    What you describe is something like: `stream.collect().asList().map(list -> applyMyComplexBusinessLogicReturningAHashMap())` – Clement May 22 '22 at 07:15