Rxjava Creating Observables -Defer

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ù)了。

代碼很簡單就不貼了,歡迎指正,謝謝。


code
log
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容