【问题标题】:How should I use Mono.zipWith when including a function that returns a Mono?包含返回 Mono 的函数时,我应该如何使用 Mono.zipWith?
【发布时间】:2019-04-15 10:20:29
【问题描述】:

我有一个 Mono,我想将它与另一个 Mono 合并,如:

val firstMono = Mono.just("thing");
val secondMono = Mono.just("other thing");
val thirdMono = firstMono.zipWith(secondMono, function);

但我希望function 也返回一个Mono没有Mono<Mono<?>> 结尾

我能想到的最好的是:

val thirdMono = firstMono.zipWith(secondMono, function)
                          .flatMap(identity());

但这似乎有点不合时宜。

我也想过

val thirdMono = firstMono.zipWith(secondMono)
                         .flatMap(function);

但在这种情况下,我必须让 function 接受 Tuple2 而不是单独的参数,这更难看。

有什么想法吗?

【问题讨论】:

  • val thirdMono = firstMono.zipWith(secondMono).flatMap(pair -> function(pair.getT1(), pair.getT2())); ...
  • 是的,我也有这个 - 工作,但使 Mono 链丑陋......可能,我正在寻找不存在的东西 - 一些识别我的操作员我与另一个 Mono 一起工作。 .flatZipWith 会很好...
  • 我会选择var thirdMono = firstMono.flatMap(left -> secondMono.flatMap(right -> function(left, right)));,但我想这是否“更漂亮”还有待商榷。

标签: java spring-webflux project-reactor


【解决方案1】:

我认为你的解决方案已经足够好了。

如果您认为它看起来像 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))

【讨论】:

  • 谢谢 - 我想我会坚持我的 flatMap(identity()) 解决方案 - 只是想知道我是否遗漏了什么......
猜你喜欢
  • 1970-01-01
  • 2012-11-01
  • 2022-01-01
  • 2019-02-20
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多