当包含 returns 一个 Mono 的函数时,我应该如何使用 Mono.zipWith?
How should I use Mono.zipWith when including a function that returns a Mono?
我有一个 Mono
,我想与另一个 Mono
组合,如:
val firstMono = Mono.just("thing");
val secondMono = Mono.just("other thing");
val thirdMono = firstMono.zipWith(secondMono, function);
但我希望 function
也 return 一个 Mono
, 没有 以 Mono<Mono<?>>
我能想到的最好的是:
val thirdMono = firstMono.zipWith(secondMono, function)
.flatMap(identity());
但这似乎有点乱。
我也想到了
val thirdMono = firstMono.zipWith(secondMono)
.flatMap(function);
但在那种情况下,我必须让 function
接受 Tuple2
而不是单个参数,这更丑陋。
有什么想法吗?
我认为你的解决方案足够好。
如果您认为它看起来像 hack,您可以将它放在一个单独的实用程序方法中,并在找到更好的解决方案时更改它。类似于:
private static <T1, T2, O> Function<Mono<T1>, Publisher<O>> flatZipTransformer(
Mono<T2> p2, BiFunction<T1, T2, Mono<O>> function) {
return p1 -> Mono.zip(p1, p2, function).flatMap(Function.identity());
}
现在您可以像这样使用它:
firstMono.transform(flatZipTransformer(secondMono, function))
我有一个 Mono
,我想与另一个 Mono
组合,如:
val firstMono = Mono.just("thing");
val secondMono = Mono.just("other thing");
val thirdMono = firstMono.zipWith(secondMono, function);
但我希望 function
也 return 一个 Mono
, 没有 以 Mono<Mono<?>>
我能想到的最好的是:
val thirdMono = firstMono.zipWith(secondMono, function)
.flatMap(identity());
但这似乎有点乱。
我也想到了
val thirdMono = firstMono.zipWith(secondMono)
.flatMap(function);
但在那种情况下,我必须让 function
接受 Tuple2
而不是单个参数,这更丑陋。
有什么想法吗?
我认为你的解决方案足够好。
如果您认为它看起来像 hack,您可以将它放在一个单独的实用程序方法中,并在找到更好的解决方案时更改它。类似于:
private static <T1, T2, O> Function<Mono<T1>, Publisher<O>> flatZipTransformer(
Mono<T2> p2, BiFunction<T1, T2, Mono<O>> function) {
return p1 -> Mono.zip(p1, p2, function).flatMap(Function.identity());
}
现在您可以像这样使用它:
firstMono.transform(flatZipTransformer(secondMono, function))