Defer — do not create the Observable until the observer subscribes, and create a fresh Observable for each observer

The Defer operator waits until an observer subscribes to it, and then it generates an Observable, typically with an Observable factory function. It does this afresh for each subscriber, so although each subscriber may think it is subscribing to the same Observable, in fact each subscriber gets its own individual sequence.
In some circumstances, waiting until the last minute (that is, until subscription time) to generate the Observable can ensure that this Observable contains the freshest data.
上文是官網(wǎng)介紹,附上連接:ReactiveX;里邊有兩個點:
1.直到訂閱時生成Observable,可以確保此Observable包含最新的數(shù)據(jù)。
2.為每個接收者生成一個Observable,雖然不同接收者訂閱了相同的Observable,但實際上每個接收者都有自己單獨的序列。
代碼是來驗證這兩部分的:
關于訂閱時生成Observable,對比第20行和30行和下圖的log,observable在開始發(fā)送事件時會打印“observable be subscribe”
在頁面創(chuàng)建時會先輸出“range111","range112"。點擊defer按鈕時觸發(fā)點擊事件,訂閱第20行生成的observable。
關于每個接收者都有單獨的序列,第一個接收者在subscribe時接收了返回值disposable(33行),第二個接收者的事件序列在新的線程中做了一個變換工作,這里調用第一個接收者的disposable.dispose()。
還有我是在新的線程中做的事件發(fā)送,這樣兩個接收者的事件在不同的線程中發(fā)送。如果兩個observable在同一個線程中發(fā)送數(shù)據(jù)是會順序執(zhí)行的,這樣調用disposable.dispose()時第一個接收者已經(jīng)接受完數(shù)據(jù)了。
代碼很簡單就不貼了,歡迎指正,謝謝。

