SpringWebFlux04操作符04zip

编程

zip操作符示意图如下图所示。

zip可以从两个Flux/Mono流中,每次各取一个元素,组成一个二元组:

# 在这个类:reactor.core.publisher.Flux

public static <T1, T2> Flux<Tuple2<T1, T2>> zip(Publisher<? extends T1> source1, Publisher<? extends T2> source2);

# 在这个类:reactor.core.publisher.Mono

public static <T1, T2> Mono<Tuple2<T1, T2>> zip(Mono<? extends T1> p1, Mono<? extends T2> p2);

下面使用案例阐述zip操作符的用法。案例代码如下:

package com.test.reactor;

import reactor.core.publisher.Flux;

import reactor.test.StepVerifier;

import java.time.Duration;

/**

* zip操作符测试

*/

public class ZipOperationDemo {

public static void main(String[] args) {

String desc = "I am Reactor";

StepVerifier.create(

// 将字符串拆分为一个一个的单词并以每500ms/个的速度发出

Flux.zip(Flux.fromArray(desc.split("\s+"))

, Flux.interval(Duration.ofMillis(500)))

// 打印

.doOnNext(System.out::print))

// 验证发出3个元素

.expectNextCount(3)

.verifyComplete();

}

}

执行案例代码,得到如下结果:

[I,0][am,1][Reactor,2]

在举一个例子

package com.test.reactor;

import reactor.core.publisher.Flux;

import reactor.test.StepVerifier;

import java.time.Duration;

/**

* zip操作符测试

*/

public class ZipOperationDemo2 {

public static void main(String[] args) {

String desc = "I am Reactor";

String desc2 = "cool moon 888";

StepVerifier.create(

Flux.zip(Flux.fromArray(desc.split("\s+"))

, Flux.fromArray(desc2.split("\s+")))

// 打印

.doOnNext(System.out::print))

// 验证发出3个元素

.expectNextCount(3)

.verifyComplete();

}

}

输出结果如下:

[I,cool][am,moon][Reactor,888]

 

以上是 SpringWebFlux04操作符04zip 的全部内容, 来源链接: utcz.com/z/513212.html

回到顶部