[英]Chaining Java Reactor Monos with filter and Map
I am trying to call multiple services (using Java Reactor) and the output of one service would determine whether the next service should be called or not. 我正在尝试调用多个服务(使用Java Reactor),一个服务的输出将确定是否应调用下一个服务。
The line 线
.filter(details -> details != null && StringUtils.isNotBlank(details.getFName))
gives error since "details" is being interpreted as a Mono. 给出错误,因为“详细信息”被解释为Mono。
If I change the code to use flatMap instead of Map, it works fine but I want a synchronous response as I need to wait for everything to complete before I can generate credentials. 如果我更改代码以使用flatMap而不是Map,则可以正常工作,但是我需要同步响应,因为在生成凭据之前,我需要等待所有操作完成。
.map(session -> dao.getDetails(session.getLogin()))
.filter(details -> details != null && StringUtils.isNotBlank(details.getFName))
Below is the code having issue. 下面是有问题的代码。
Mono<Credentials> response = dao.validateSession(sessionId)
.filter(session -> session != null && StringUtils.isNotBlank(session.getLogin()))
.map(session -> dao.getDetails(session.getLogin()))
.filter(details -> details != null && StringUtils.isNotBlank(details.getFName))
.map(details -> dao.generateCredentials())
.cast(Credentials.class);
The below code solved the issue. 以下代码解决了该问题。
Map returns a <Mono<Mono>> while flatMap returns a <Mono>
Mono<Credentials> response = dao.validateSession(sessionId)
.filter(session -> session != null && StringUtils.isNotBlank(session.getLogin()))
.map(session -> dao.getDetails(session.getLogin()))
.flatMap(session->session)
.filter(details -> details != null && StringUtils.isNotBlank(details.getFName))
.map(details -> dao.generateCredentials())
.flatMap(credentials -> credentials);
You can simplify like this: 您可以像这样简化:
Mono<Credentials> response = dao.validateSession(sessionId)
.filter(session -> StringUtils.isNotBlank(session.getLogin()))
.flatMap(session -> dao.getDetails(session.getLogin()))
.filter(details -> StringUtils.isNotBlank(details.getFName))
.flatMap(details -> dao.generateCredentials());
I've changed the operator used to simplify, but I think the last step require the details
object to be used as arguments of generateCredentials
method. 我已经更改了用于简化的运算符,但我认为最后一步要求将details
对象用作generateCredentials
方法的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.