rxjava2 中的运算符延迟

operator delay in rxjava2

我是新手 rxjava2.when 我读过有关它的书,但我有一些我不了解的关于操作员延迟的内容。

We can postpone emissions using the delay() operator. It will hold any received emissions and delay each one for the specified time period. If we wanted to delay emissions by three seconds, we could do it like this:

 public static void main(String[] args) {

    Observable.just("Alpha", "Beta", "Gamma" ,"Delta",
            "Epsilon")
            .delay(3000, TimeUnit.SECONDS)
            .subscribe(s -> System.out.println("Received: " + s));

    sleep(3000);
}

public static void sleep(long millis) {
    try {
        Thread.sleep(millis);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

上述代码片段的输出如下: 测试版 Α 伽马 三角洲 小量

我认为输出只有 "Alpha",因为他们说

Because delay() operates on a different scheduler (such as Observable.interval()), we need to leverage a sleep() method to keep the application alive long enough to see this happen. Each emission will be delayed by three seconds

延迟 3 秒,我认为存在 "Alpha" 的发射,但它发射了可观察到的所有发射。

根据 Documentation,延迟运算符 'delay' 在给定时间内发出。

所以,它会显示'Alpha'、'Beta'、'Gamma'、'Delta'、'Epsilon',而不仅仅是'Alpha'。

println("started")

val subscribe = Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon")
        .delay(3, TimeUnit.SECONDS)
        .subscribe { s -> println("Received: $s") }

此代码将生成 3 秒后发出的所有五个字符串。

  • 2019-02-21 18:02:30.285我:开始了
  • 2019-02-21 18:02:33.459 I:接收:Alpha
  • 2019-02-21 18:02:33.464 I: 收到: Beta
  • 2019-02-21 18:02:33.466 I: 收到: Gamma
  • 2019-02-21 18:02:33.467 I: 收到: Delta
  • 2019-02-21 18:02:33.469 I: 接收: Epsilon

这就是你想要的吗?

val source1 = Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon")

val source2 = Observable.interval(3000, TimeUnit.MILLISECONDS)

val observable = Observable.zip(source1, source2, object : BiFunction<String, Long, Any> {
    override fun apply(t1: String, t2: Long): Any {
        Log.d("Sometag", "Received $t1")
        return "Something"
    }
}).subscribe()

输出

2019-02-21 13:40:15.502  D/Sometag: Received Alpha
2019-02-21 13:40:18.502  D/Sometag: Received Beta
2019-02-21 13:40:21.502  D/Sometag: Received Gamma
2019-02-21 13:40:24.502  D/Sometag: Received Delta
2019-02-21 13:40:27.502  D/Sometag: Received Epsilon

在您的情况下,延迟操作只会将所有流延迟 3 秒,并且所有元素将立即发出,请参阅 rx 文档 http://reactivex.io/documentation/operators/delay.html

如果你想将每个元素延迟 3 秒,你可以这样做:

       Observable.fromArray("Alpha", "Beta", "Gamma", "Delta",
            "Epsilon")
            .concatMap(s -> Observable.just(s).delay(3, TimeUnit.SECONDS))
            .subscribe(s -> System.out.println("Received: " + s));