简体   繁体   中英

How do I return a Mono<List<Object>> into a HashMap?

I have a hashmap of <Integer, QueryObj> that I need to iterate over and call an external service with. The method signature of my external service is like:

private Mono<List<ReturnedObj>> fetchList(QueryObj query)

and I've been able to verify that it's working and returns a list of what I need. However, I'm unsure of what my next steps should be and what my response type in the parent method should be in order to maintain reactive practices. Basically, I want to transform the Map<Integer, Query> into Map<Integer, Mono<List<ReturnedObj>> . I am wondering if Map<Integer, Mono<List<ReturnedObj>> is even possible? Does it need to be Mono<Map<K<V>> ?

Here is the current code snippet - it doesn't throw an error, but rather returns an empty result. I'm thinking the mix of imperative and reactive programming doesn't wait for the results of fetchList() to populate the response.

Map<Integer, QueryObj> queryMap = getQueries(); // setup
return queryMap.entrySet()
                    .stream()
                    .collect(Collectors.toMap(
                            e -> e.getKey(), e -> {
                                try {
                                     return fetchList(e.getValue());
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                                return null;
                            }));
        }

Would greatly appreciate any help. I am fairly new to this.

Thanks all for the suggestions - I ended up finding a solution that works for me. I ended up making my whole flow reactive (as I should have done from the start) and changed the return type of my method to be Mono<Map<Integer, List>. I used a Flux.fromIterable() with flatMap() on the entrySet and collectMap to get the results together into a map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM