The most efficient way to split a Flux to multiple Fluxes in Reactor 3

徘徊边缘 提交于 2020-01-15 07:30:12

问题


In Reactor 3, what's the most efficient way to split a heterogeneous flux to multiple fluxes by pattern matching? (And subsequent operations on each flux may be very different)

For example,

Source Flux: a->b->c->a->b->c
 ||
 vv
A Flux: a->a->a
B Flux: b->b->b
C Flux: c->c->c

I'm new to reactive programming, and the only solution I come up with is share()+filter(), like

val shared = flux.share();
shared.filter(x -> x.tag=='a').subscribe(a -> consumeA(a));
shared.filter(x -> x.tag=='b').subscribe(b -> consumeB(b));
shared.filter(x -> x.tag=='c').subscribe(c -> consumeC(c));

Is this the best solution, or is there any better paradigm for this problem?


回答1:


If the number of groups is fairly low, then you can use Flux.groupBy referenced in the project reactor docs

For example:

Flux<String> flux = Flux.just("a1", "b1", "c1", "a2", "b2", "c2")
        .groupBy(s -> s.charAt(0))
        .concatMap(groupedFlux -> groupedFlux
                .startWith("Group " + groupedFlux.key()));

StepVerifier.create(flux)
        .expectNext("Group a", "a1", "a2")
        .expectNext("Group b", "b1", "b2")
        .expectNext("Group c", "c1", "c2")
        .verifyComplete();

You can use groupedFlux.key() to vary the operations performed for each group.



来源:https://stackoverflow.com/questions/55892421/the-most-efficient-way-to-split-a-flux-to-multiple-fluxes-in-reactor-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!