[英]How to create Hot Observable in RxJS 5
我使用 RxJS 4 創建 Hot Observable,如官方文檔中的描述
但是RxJS 5 遷移指南並沒有解釋如何創建 Hot Observable。
const source = Observable.create((observer) => {
asynCall((data) => {
observer.onNext(data)
})
})
const published = source.publish()
published.connect()
published.subscribe((data) => {
console.log(data)
})
使用 Rx5 我有以下錯誤:
未捕獲的類型錯誤:source.publish 不是函數(...)
您可以使用.publish().refCount()
(或.share()
作為別名)
var source = Rx.Observable.interval(1000)
.take(5)
.publish().refCount();
source.subscribe( item => console.log(`-: ${item}`));
setTimeout(() => {
source.subscribe( item => console.log(`--: ${item}`));
}, 2500);
http://jsbin.com/cupibitehu/1/edit?js,console
上面設置了兩個訂閱以顯示延遲訂閱將從當前發出的地方開始,而不是重播以前發出的結果。
記錄以下內容
"-: 0"
"-: 1"
"-: 2"
"--: 2"
"-: 3"
"--: 3"
"-: 4"
"--: 4"
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-share
這是對冷熱可觀察量的看法
Hot Observable
任何不會在訂閱時產生新生產者的 observables(如果 obs.subscribe() 在 observable 上被調用,那么這個新創建的訂閱不應該有一個新的 Observer.next(val)。它應該使用舊的和因此獲取當前時間點的值)
Cold Observable
任何在訂閱時產生新生產者的 observable - obs.subscribe() 基本上創建了 Observer.next() - 一個新的訂閱源生產者。 Angular 中的所有 HttpCLient observables 都是這種類型。 對於組件中的每個 obs.subscribe,您會看到 API 僅針對該訂閱發出值。 每次都是從頭開始
因此,上面的publish() 和refCount() rxjs 操作符基本上所做的是創建一個observable,它同時表現得像一個hot observable 和cold observable。 Hot observable - 因為沒有產生新的源值和 Cold Observable - 因為它只有在訂閱發生時才開始發出值 - obs.subscribe() 被第一次調用
所以為了產生一個不需要訂閱就存在的 HotObservable,然后 publish() 和 connect() 就可以了
var source = Rx.Observable.create({<some obj>})
.publish();
source.connect();
source.subscribe( item => console.log(`-: ${item}`));
setTimeout(() => {
source.subscribe( item => console.log(`--: ${item}`));
}, 2500);
您不會在控制台中看到任何內容,因為 observable 會在訂閱發生時發出值。 注意如果在觀察到的發光值的延遲,那么你可能會看到他們在訂閱我想給信貸對本文以及:它很好地解釋https://blog.thoughtram.io/angular/2016/ 06/16/cold-vs-hot-observables.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.