Search code examples
javaquarkussmallrye

Mutinity: how to combine a Uni and a Multi?


I have the following method:

 public Uni<JsonObject> getHMOStats(String outcode);

That returns a Uni, which value needs to be set in the OutcodeStats objects created by this method:

 private Multi<OutcodeStats> getOutcodeStats() {
        return Multi.createFrom().items(UkRegions.values())
                .invoke(region -> log.infof("Fetching stats for region %s", region.name()))
                .flatMap(region -> outcodeStatsService.getByRegion(apiKey, region.name()).toMulti())
                .flatMap(regionStats -> Multi.createFrom().items(regionStats.getData().stream()))
                .invoke(outcodeStats -> log.infof("Processing %s", outcodeStats.getOutcode()))
                .map(this::setEffectiveDate)
                .map(outcodeStats -> outcodeStats.setHmoStats(hmoService.getHMOStats(outcodeStats.getOutcode()))))  <--- PSEUDO CODE

    }

Unfortunately, I have no idea how to combine the two in order to set the hmoStats attribute of the OutcodeStats object.

One solution could be to make getHMOStats not returning a Uni, but I do not think that is the way to go.

Thanks for your attention.


Solution

  • I think you want to do

                    .onItem()
                    .transformToUniAndMerge(outcodeStats ->
                            hmoService.getHMOStats(outcodeStats.getOutcode())
                                    .onItem()
                                        .transform(hmoStats -> {
                                            outcodeStats.setHmoStats(hmoStats);
                                            return outcodeStats;
                                        }
                                    ));