2017-07-25 117 views
1

我正在嘗試學習RxJS,並試圖構建我認爲是一個簡單而直接的示例。創建一個間隔生成的隨機數的可觀察值,然後根據該可觀察值使用另外兩個可觀察值來跟蹤已經看到的最低值和最高值。RxJS:鏈式觀察量不使用相同的根可觀察值

rStStream似乎表現得像預期的一樣,minStream和maxStream都顯示正確跟蹤。我遇到的問題是,當執行它時,似乎rngStream,minStream和maxStream在每個時間間隔上都有不同的隨機數。我試圖瞭解,如果這是預期或如果我剛剛設置了一些錯誤。

我的目標將是一個輸出類似:

[27, 27, 27] 
[13, 13, 27] 
[90, 13, 90] 
[42, 13, 90] 
... 

let rngStream = Rx.Observable 
 
    .interval(1000) 
 
    .map(() => Math.ceil(Math.random()*100)) 
 
    .take(5); 
 

 
// Track the lowest number we've seen. 
 
let minStream = rngStream 
 
    .startWith(100) 
 
    .scan((x, y) => Math.min(x, y)) 
 

 
// Track the highest number we've seen. 
 
let maxStream = rngStream 
 
    .startWith(0) 
 
    .scan((x, y) => Math.max(x, y)) 
 

 
Rx.Observable.zip(rngStream, minStream, maxStream) 
 
    .subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.2/Rx.min.js"></script>

回答

2

https://www.youtube.com/watch?v=3LKMwkuK0ZE

這顯卡其實澄清了很多東西給我。特別是在32點的時候,他提到了.share,它使得可觀察的組播成爲可能。默認情況下,每個用戶都會得到自己的副本。因此,修復看起來是這樣的:

let rngStream = Rx.Observable 
 
    .interval(1000) 
 
    .map(() => Math.ceil(Math.random()*100)) 
 
    .take(5) 
 
    .share(); 
 

 
// Track the lowest number we've seen. 
 
let minStream = rngStream 
 
    .startWith(100) 
 
    .scan((x, y) => Math.min(x, y)) 
 

 
// Track the highest number we've seen. 
 
let maxStream = rngStream 
 
    .startWith(0) 
 
    .scan((x, y) => Math.max(x, y)) 
 

 
Rx.Observable.zip(rngStream, minStream, maxStream) 
 
    .subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.2/Rx.min.js"></script>