文章0 | 阅读 9576 | 点赞0
之前文章也介绍过了Mono和Flux的静态创建方法,这里有两种方法能够更加随意的生成Mono或是Flux:
@Test
public void generateFlux() {
Flux<Object> flux = Flux.
generate(
()-> 0,
(i, sink) -> {
sink.next(i*i);
if (i == 5) sink.complete();
return ++i;
},
state -> log.warn("the final state is:{}", state)
).
log();
flux.subscribe();
}
@Test
public void createMono() {
Mono<Object> mono = Mono
.create(sink -> {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list.add(i);
}
sink.success(list);
})
.log();
StepVerifier.create(mono)
.expectSubscription()
.expectNext(Arrays.asList(0,1,2,3,4))
.verifyComplete();
}
@Test
public void createFlux() {
Flux<Object> flux = Flux
.create(sink -> {
for (int i = 0; i < 5 ; i++) {
sink.next(i*i);
}
sink.error(new RuntimeException("fake a mistake"));
sink.complete();
})
.log();
StepVerifier.create(flux)
.expectSubscription()
.expectNext(0,1,4,9,16)
.expectError(RuntimeException.class)
.verify();
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://fanfanzhisu.blog.csdn.net/article/details/107858943
内容来源于网络,如有侵权,请联系作者删除!