什么是将Flux与Mono进行压缩的适当方法?

huangapple go评论128阅读模式
英文:

What is the proper way of zipping Flux with Mono?

问题

以下是翻译好的内容:

有一个 Mono<A>Flux<B>,我们需要创建一个类似这样的元组流:

Mono<A> monoA = createMono(); // {a}
Flux<B> fluxB = createFlux(); // {b1, b2, ... b100, ...}

Flux<Tuple<A,B>> zippedTuples = magicZip(monoA, fluxB); // { (a:b1), (a:b2), ... (a:b100), ...}

编写 magicZip 函数的正确(或标准)方法是什么?

英文:

There's a Mono&lt;A&gt; and Flux&lt;B&gt;, and we need to create a flux of tuples like this:

Mono&lt;A&gt; monoA = createMono(); // {a}
Flux&lt;B&gt; fluxB = createFlux(); // {b1, b2, ... b100, ...}

Flux&lt;Tuple&lt;A,B&gt;&gt; zippedTuples = magicZip(monoA, fluxB); // { (a:b1), (a:b2), ... (a:b100), ...}

What is the proper (or standard) way to write the magicZip function?

答案1

得分: 1

你可以创建这个方法:

private <T> Flux<Tuple2<T, T>> magicZip(Mono<T> mono, Flux<T> flux) {
    Flux<T> repeatableMono = mono.repeat();
    return flux.zipWith(repeatableMono);
}

字符串类型的示例:

Flux<Tuple2<String, String>> test = magicZip(getMono(), getFlux()).doOnNext(objects -> System.out.println(objects.getT1() + objects.getT2()));
test.blockLast();
英文:

You can create this method:

private &lt;T&gt;Flux&lt;Tuple2&lt;T, T&gt;&gt; magicZip(Mono&lt;T&gt; mono, Flux&lt;T&gt; flux) {
	Flux&lt;T&gt; repeatableMono = mono.repeat();
	return flux.zipWith(repeatableMono);
}

Example for the String type:

    Flux&lt;Tuple2&lt;String, String&gt;&gt; test = magicZip(getMono(), getFlux()).doOnNext(objects -&gt; System.out.println(objects.getT1() + objects.getT2()));
	test.blockLast();

答案2

得分: 0

我认为使用zip函数是不可能的,因为它生成的元素数量与两者中最小的数量相同。

我认为你可以实现这样的方式:

Flux<A> fluxA = monoA.flux();
Flux<Tuple2<A,B>> zippedTuples = fluxB.flatMap(b -> fluxA.map(a -> Tuples.of(a,b)));
英文:

I think that with zip function is not possible because it produces as many elements as the smallest of two.

The way I think you can achive this is:

Flux&lt;A&gt; fluxA = monoA.flux();
Flux&lt;Tuple2&lt;A,B&gt;&gt; zippedTuples =fluxB.flatMap(b -&gt; fluxA.map(a -&gt; Tuples.of(a,b)));

huangapple
  • 本文由 发表于 2020年4月6日 13:49:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/61053646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定