官术网_书友最值得收藏!

Observable.defer()

Observable.defer() is a powerful factory due to its ability to create a separate state for each Observer. When using certain Observable factories, you may run into some nuances if your source is stateful and you want to create a separate state for each Observer. Your source Observable may not capture something that has changed about its parameters and send emissions that are obsolete. Here is a simple example: we have an Observable.range() built off two static int properties, start and count.

If you subscribe to this Observable, modify the count, and then subscribe again, you will find that the second Observer does not see this change:

    import io.reactivex.Observable;

public class Launcher {

private static int start = 1;
private static int count = 5;

public static void main(String[] args) {

Observable<Integer> source = Observable.range(start,count);

source.subscribe(i -> System.out.println("Observer 1: " + i));

//modify count
count = 10;

source.subscribe(i -> System.out.println("Observer 2: " + i));
}
}

The output is as follows:

    Observer 1: 1
Observer 1: 2
Observer 1: 3
Observer 1: 4
Observer 1: 5
Observer 2: 1
Observer 2: 2
Observer 2: 3
Observer 2: 4
Observer 2: 5

To remedy this problem of Observable sources not capturing state changes, you can create a fresh Observable for each subscription. This can be achieved using Observable.defer(), which accepts a lambda instructing how to create an Observable for every subscription. Because this creates a new Observable each time, it will reflect any changes driving its parameters:

    import io.reactivex.Observable;

public class Launcher {

private static int start = 1;
private static int count = 5;

public static void main(String[] args) {

Observable<Integer> source = Observable.defer(() ->
Observable.range(start,count));

source.subscribe(i -> System.out.println("Observer 1: " + i));

//modify count
count = 10;

source.subscribe(i -> System.out.println("Observer 2: " + i));
}
}

The output is as follows:

    Observer 1: 1
Observer 1: 2
Observer 1: 3
Observer 1: 4
Observer 1: 5
Observer 2: 1
Observer 2: 2
Observer 2: 3
Observer 2: 4
Observer 2: 5
Observer 2: 6
Observer 2: 7
Observer 2: 8
Observer 2: 9
Observer 2: 10

That's better! When your Observable source is not capturing changes to the things driving it, try putting it in Observable.defer(). If your Observable source was implemented naively and behaves brokenly with more than one Observer (for example, it reuses an Iterator that only iterates data once), Observable.defer() provides a quick workaround for this as well.

主站蜘蛛池模板: 华阴市| 永清县| 民权县| 三原县| 兴仁县| 郁南县| 安丘市| 睢宁县| 班戈县| 灌阳县| 日照市| 金塔县| 苍溪县| 浦北县| 库尔勒市| 吉首市| 九江县| 红桥区| 竹山县| 阿荣旗| 宿州市| 彭阳县| 瑞安市| 客服| 阳西县| 商南县| 临西县| 隆尧县| 宁城县| 张家港市| 武隆县| 墨江| 襄垣县| 库伦旗| 北辰区| 曲水县| 南岸区| 秭归县| 大港区| 邮箱| 壤塘县|