.defer() 在 RxJava 中做了什么?

What does .defer() do in RxJava?

我是 rx java 的新手,我不明白 Completable.defer 带来了什么以及为什么使用它是一个好习惯。

所以,两者有什么区别:

public Completable someMethod1() {
    return Completable.defer(() -> someMethod2());
}

public Completable someMethod1() {
    return someMethod2();
}

我可以看到在方法的实现中有一些异常处理,但这超出了我。 欣赏一下。

Defer 将确保每个订阅者都可以获得自己的源序列,独立于其他订阅者。让我用两个例子来说明:

AtomicInteger index = new AtomicInteger();

Flowable<String> source =
    Flowable.just("a", "b", "c", "d", "e", "f")
    .map(v -> index.incrementAndGet() + "-" + v)
    ;

source.subscribe(System.out:println);

source.subscribe(System.out:println);

打印

1-a
2-b
3-c
4-d
5-e
6-f
7-a
8-b
9-c
10-d
11-e
12-f

对比

Flowable<String> source =
    Flowable.defer(() -> {
        AtomicInteger index = new AtomicInteger();

        return Flowable.just("a", "b", "c", "d", "e", "f")
               .map(v -> index.incrementAndGet() + "-" + v)
               ;
    })
    ;

source.subscribe(System.out:println);

source.subscribe(System.out:println);

打印

1-a
2-b
3-c
4-d
5-e
6-f
1-a
2-b
3-c
4-d
5-e
6-f

在第二个示例中,每个订阅者都有一个状态,否则会在所有订阅者之间共享。现在,由于每个订阅者都创建了自己的单独序列,因此这两个索引项都如人们通常所期望的那样。