分裂/重新加入通量的正确方法

时间:2017-12-06 15:32:24

标签: project-reactor

以下是将Flux拆分为不同处理路径并将它们连接起来的正确/惯用方法 - 出于问题的目的,不应丢弃事件,排序不重要,内存不受限制。

Flux<Integer> beforeFork = Flux.range(1, 10);

ConnectableFlux<Integer> forkPoint = beforeFork
    .publish()
;

Flux<String> slowPath = forkPoint
        .filter(i -> i % 2 == 0)
        .map(i -> "slow"+"_"+i)
        .delayElements(Duration.ofSeconds(1))
;

Flux<String> fastPath = forkPoint
        .filter(i -> i % 2 != 0)
        .map(i -> "fast"+"_"+i)
;

// merge vs concat since we need to eagerly subscribe to
// the ConnectableFlux before the connect()
Flux.merge(fastPath, slowPath)
    .map(s -> s.toUpperCase()) // pretend this is a more complex sequence
    .subscribe(System.out:println)
;
forkPoint.connect();

我想如果filter()函数慢于%,我也可以groupBy()然后在key()上使用filter()。

请注意,我确实希望slowPath和fastPath使用来自beforeFork点的相同事件,因为beforeFork生成起来很慢。

请注意,我确实有一个更复杂的后续(即更改为range(1,100)并且预取边界周围的行为让我感到困惑) - 但我只有在上述代码段合法的情况下才有意义。

0 个答案:

没有答案
相关问题