[英]Return a value from a Mono call
Newbie to reactive programming in JAVA, I have a function buildRow
that makes an async call to get hold of id and then use that determine a boolean value, this function always return's before async call gets completed. 我如何使它仅在异步调用完成并确定 boolean 值后返回?
public Row buildRow(Row row) {
Mono<Long> id = reader.getColumn(row.getId());
id
.doOnNext(value-> {
boolean isEnabled = reader.isEnabled(value);
// This is getting returned second
testRow(row, isEnabled);
})
.subscribe();
// This is getting returned first
return row;
}
public Row testRow(Row row, boolean isEnabled) {
if (isEnabled) {
return row;
} else {
return new Row();
}
}
// Triggered in another function like this
map(row -> buildRow(row))
您可以将逻辑切换到该逻辑:
public Mono<Row> buildRow(Row row) {
return reader.getColumn(row.getId())
.map(reader::isEnabled)
.filter(isEnabled -> isEnabled)
.map(enabled -> row)
.switchIfEmpty(Mono.just(new Row()));
}
之后,您可以从以下位置更改 buildRow 方法的调用:
map(row -> buildRow(row))
至:
flatMap(row -> buildRow(row))
否则,在阅读器逻辑中将反应式与非反应式方法混合是没有意义的。 你混合得越多,你遇到的问题就越多。
Mono
是一个专门的Publisher
者,它只能包含零个或一个事件。
在Mono<T>
Class 中,有block()
方法:
public T block()
订阅此 Mono 并无限期阻止,直到收到下一个信号。 如果 Mono 为空,则返回该值或 null。 如果出现 Mono 错误,则会引发原始异常(如果是已检查异常,则将其包装在 RuntimeException 中)。
综上所述, block()
方法用于获取T
类型的值。 现在,您可以使用block()
方法返回您的Row
类型值。
代码如下:
public Row buildRow(Row row) {
Mono<Long> id = reader.getColumn(row.getId());
Row row = id.map(value-> {
boolean isEnabled = reader.isEnabled(value);
// use map return value
return testRow(row, isEnabled);
})
.block(); // use block to compute and then get value
// Now what you want could return
return row;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.