简体   繁体   English

合并两个 Mono 并获得通量。 然后从那个 Flux 中提取一个 Mono

[英]Merging two Mono and getting a Flux. Then extracting a Mono from that Flux

I have two Mono<T> that i have got from two different sources let us say KAFKA .我有两个Mono<T>我从两个不同的来源得到让我们说KAFKA

My intention is to merge both these Mono into a Flux<T> .我的意图是将这两个Mono合并到一个Flux<T>中。 1 1

Then use public final Mono<T> reduce(BiFunction<T,T,T> aggregator) method in Flux to create a final Mono out of it (as the response time of above two Mono may vary).然后在Flux中使用public final Mono<T> reduce(BiFunction<T,T,T> aggregator)方法创建一个最终的Mono (因为上面两个Mono的响应时间可能会有所不同)。 2 2

approach:方法:

There are many methods such as contact , zip , zipWith to use on Flux .Flux上使用的方法有很多,例如contactzipzipWith How do i arrive at a correct method to use (Two Mono to Flux conversion ie, 1 ).我如何找到正确的使用方法(两个MonoFlux转换,即1 )。

And is this REDUCE approach really correct or is there anything else could be done to improvise it ( 2 )?这种REDUCE方法真的正确吗,或者还有什么其他方法可以即兴发挥吗( 2 )? Thanks.谢谢。

If you really want to use a Flux to do this, then you'd likely want to use merge() , similar to:如果您真的想使用Flux来执行此操作,那么您可能想要使用merge() ,类似于:

Flux.merge(mono1(), mono2()).reduce((obj1, obj2) -> foo(obj1, obj2));

...where foo() fulfils the functionality of the reduce method in the question, combining both objects emitted into a single value. ...其中foo()实现了问题中reduce方法的功能,将发出的两个对象组合成一个值。 You wouldn't want to use concat() unless you want to subscribe to each Mono one at a time, waiting for each to complete, rather than all together - and the Flux.zipXXX series of operators would be used for zipping separate fluxes together, so you wouldn't want that.你不会想使用concat()除非你想一次订阅每个Mono ,等待每个完成,而不是一起完成 - 并且Flux.zipXXX系列运算符将用于将单独的通量压缩在一起,所以你不会想要那个。

However, I don't think you quite have the correct approach here for two values - if you want to put two Mono publishers into a Flux and then immediately reduce them back to a Mono , then it doesn't make much sense to use a Flux at all, since you have to wait for both the publishers to complete before emitting anything, and then you're just emitting a single value.但是,我认为您在这里对两个值没有正确的方法-如果您想将两个Mono发布者放入Flux中,然后立即将它们减少回Mono ,那么使用 a 没有多大意义Flux ,因为您必须等待两个发布者都完成才能发出任何内容,然后您只发出一个值。

Instead, I'd recommend using this variant of Mono.zip() , which allows you to do everything you need in one go, something like:相反,我建议使用Mono.zip()的这种变体,它允许您在一个 go 中完成所需的一切,例如:

Mono.zip(mono1(), mono2(), (obj1, obj2) -> foo(obj1, obj2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM