I am changing a java app to use reactive programming to allow asyncronous and nonblocking flow but I'm having trouble understanding the concepts to achieve this. A stream of siteIds are used to invoke third party APIs and eventually the response is saved into some storage.
The code I have now is blocking and I would like to remove that...
generateReport() returns a Mono< BaseResponse > object
getReportAndSave() retrieves and manipulates the report and saves it, then should return boolean.
listResult = siteIds.parallel()
.map(siteId -> generateReport(authToken, requestParams, siteId))
.map(response -> response.block(Duration.ofMinutes(asyncCallTimeout)))
.map(resp -> getReportAndSave(authToken, resp.getRequestId()))
.collect(Collectors.toList());
So far I have this which should be able to do the same except I dont know how to get a return value for listResult.
siteId.forEach(siteId -> generateReport(authToken, requestParams, siteId)
.subscribe(baseResponse -> getReportAndSave(authToken, baseResponse.getRequestId())));
listResult is a List of Booleans, saying if each siteId has successfully been saved into a blob storage.
final Flux<ResultWrapperBean> resultFlux = Flux.fromIterable(siteIds)
// Since generateReport() returns Mono, here you should use flatMap instead of map.
.flatMap(siteId -> generateReport(authToken, requestParams, siteId))
// Use a wrapper bean to save the request id and request result.
.map(resp -> new ResultWrapperBean(resp.getRequestId(), getReportAndSave(authToken, resp.getRequestId())));
resultFlux.subscribe(resultBean -> log.info("RequestId: {}, and request result is {}", resultBean.getRequestId(), resultBean.getResult()));
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.