webflux - map与flatmap区别
- map 是同步转换
- flatmap是异步的
map
@Test
public void mapTest() {
Flux.range(1, 4)
.log()
.map(e -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
return 2 * e;
}).subscribe(System.out::println);
}
结果:
22:14:33.702 [main] INFO reactor.Flux.Range.1 - | onSubscribe([Synchronous Fuseable]...
22:14:33.704 [main] INFO reactor.Flux.Range.1 - | request(unbounded)
22:14:33.705 [main] INFO reactor.Flux.Range.1 - | onNext(1)
2
22:14:34.705 [main] INFO reactor.Flux.Range.1 - | onNext(2)
4
22:14:35.706 [main] INFO reactor.Flux.Range.1 - | onNext(3)
6
22:14:36.706 [main] INFO reactor.Flux.Range.1 - | onNext(4)
8
22:14:37.707 [main] INFO reactor.Flux.Range.1 - | onComplete()
flatmap
@Test
public void flatMapTest() throws InterruptedException {
Flux.range(1, 4)
.log()
.flatMap(e -> {
return Flux.just(e * 2).delayElements(Duration.ofSeconds(1));
}).subscribe(System.out::println);
TimeUnit.SECONDS.sleep(10);
}
结果:
22:11:31.160 [main] INFO reactor.Flux.Range.1 - | onSubscribe([Synchronous Fuseable]...
22:11:31.162 [main] INFO reactor.Flux.Range.1 - | request(256)
22:11:31.162 [main] INFO reactor.Flux.Range.1 - | onNext(1)
22:11:31.193 [main] INFO reactor.Flux.Range.1 - | onNext(2)
22:11:31.194 [main] INFO reactor.Flux.Range.1 - | onNext(3)
22:11:31.194 [main] INFO reactor.Flux.Range.1 - | onNext(4)
22:11:31.195 [main] INFO reactor.Flux.Range.1 - | onComplete()
4
6
8
2
可以看到并不是有序输出