简体   繁体   English

RxJava Observable/Flowable 上的运算符将发射延迟 n 项

[英]Operator on RxJava Observable/Flowable to delay emission by n items

I'd like to transform a Flowable so that it defers emitting items until a specified number of items is collected, and then emits them to downstream in FIFO order maintaining constant delayed item count.我想转换一个Flowable以便它推迟发射项目,直到收集到指定数量的项目,然后以 FIFO 顺序将它们发射到下游,保持恒定的延迟项目计数。 Once upstream signals onComplete, the queued items should be flushed to downstream before emitting onComplete:一旦上游发出 onComplete 信号,排队的项目应该在发出 onComplete 之前被刷新到下游:

(in this example delayed item number is 3) (在本例中延迟项目编号为 3)

1 2 3 4 5 6 7 |
      1 2 3 4 5 6 7 |

I don't see any existing operators that do this or can be modified to get that behavior.我没有看到任何现有的运营商这样做或可以修改以获得该行为。 Observable.delay seems to support only time-based delay, not count-based delay. Observable.delay似乎只支持基于时间的延迟,不支持基于计数的延迟。

It should be easy to implement a custom operator to achieve this, but maybe there's a simpler way with existing operators?实现自定义运算符来实现这一点应该很容易,但也许现有运算符有更简单的方法?

You can publish a sequence, skip the last N, then append the last N back:您可以发布一个序列,跳过最后 N,然后追加最后 N:

Flowable.range(1, 7)
    .flatMap(v -> Flowable.timer(v * 200, TimeUnit.MILLISECONDS).map(w -> v))
    .doOnNext(v -> System.out.println(v))
// -------------------------------------------------------------------
    .publish(f -> 
        f.skipLast(3).mergeWith(f.takeLast(3))
    )
// -------------------------------------------------------------------
    .blockingSubscribe(v -> System.out.println("<-- " + v));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM