Issue
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.
Solution
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.
Answered By - FlackoNeil
Answer Checked By - Katrina (JavaFixing Volunteer)