I'm using reactive WebClient to build an API that communicates with 2 other APIs. API2 needs to get Information from API1, and then my service combines and returns both information. Resource:
@GetMapping("monoMedication/{medID}")
public Mono<Object> getMonoMedication(@PathVariable String medID) throws SSLException {
Mono<Login> Login =createWebClient()
.post()
.uri("URI_LOGIN_API1" )
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject(body))
.retrieve()
.bodyToMono(Login.class);
return Login.map(login-> {
Mono<String> medicationBundles = null;
try {
medicationBundles = createWebClient()
.post()
.uri("URI_API1_GET_DATA")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject("Information"))
.header("Authorization", login.getSessionId())
.retrieve()
.bodyToMono(String.class);
} catch (SSLException e) {
e.printStackTrace();
}
return medicationBundles.map(bundles_string -> {
try {
List<Object> bundle_list = mapper.readValue(bundles_string, new TypeReference<List<Object>>(){});
bundle_list.forEach(bundle-> processBundle(bundle,medicationList));
return medicationList;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
})
})
}
The Function:
List<String> medicationList = new ArrayList<>();
private void processBundle(Object bundle, List<String> medicationlist) {
//do something to get id from bundle
String ID = bundle.getID();
// if i add something to medicationList.add(ID) here, it is in the required return of my API
Mono<String> Medication =
webClientBuilder.build()
.get()
.uri("URI_API2_GET_DATA"+ID)
.retrieve()
.bodyToMono(String.class);
Medication.map(medication_ID -> {
//do something to get information from medication_ID
String info = medication_ID.getInfo();
//this Information comes after the required return
return medicationList.add(info+ID);
}).subscribe();
}
My Problem is, that the return comes before the required last map is completed. I somehow missing something. I tried different approaches with e.g. then(), thenMany(), thenReturn() in different positions. Is there a way to do this? If there is a perhaps already a finished simple example, that would also help!