簡體   English   中英

RxJS-如何映射/切換一個可觀察對象,並為每個發射值添加均值計算?

[英]RxJS - How can I map/switch a Subject Observable and add a mean calculation to every emitted value?

我對RxJS相當陌生,我想執行以下操作:

想象一下,我正在編寫一種跟蹤時間的方法。 此方法將觀察一個Subject,該Subject將發出類似於以下的值: [12, 49, -2, 26, 5, ...]

我該如何將其轉換為另一個Observable,為每個值隨時間增加平均值?

[
  {
    temperature: 12,
    mean: 12
  },
  {
    temperature: 49,
    mean: 30.5
  },
  {
    temperature: -2,
    mean: 19.67
  },
  {
    temperature: 26,
    mean: 21.25
  },
  {
    temperature: 5,
    mean: 18
  },
  ...
]

我正在努力的困難是均值計算應使用所有先前的值進行。

有沒有辦法做到這一點? 實際上,我需要添加更多數據並計算其他值,但這是我要做的要旨。

像在reduce陣列上一樣使用掃描。 傳遞{num:0,total:0,mean:0}的起始累加器,每次迭代使num遞增,將當前溫度添加到總溫度中並計算平均值。 將可觀察對象視為隨時間推移發生的數組有時可以幫助可視化它們。

 const { from, timer, zip } = rxjs; const { scan } = rxjs.operators; const temps = [12, 49, -2, 26, 5]; // Let's do it with an array console.log( temps.reduce( (accumulator, temp) => ({ num: accumulator.num + 1, temp: temp, total: accumulator.total + temp, mean: (accumulator.total + temp) / (accumulator.num + 1) }), { num: 0, temp: 0, total: 0, mean: 0 } ) ); const temps$ = from(temps); const timer$ = timer(0, 1500); var tempsOverTime$ = zip(temps$, timer$, (temp, _) => temp); // Now let's do the same thing with an observable over time. tempsOverTime$ .pipe( scan( (accumulator, temp) => ({ num: accumulator.num + 1, temp: temp, total: accumulator.total + temp, mean: (accumulator.total + temp) / (accumulator.num + 1) }), { num: 0, temp: 0, total: 0, mean: 0 } ) ) .subscribe(a => { console.log({ temp: a.temp, mean: a.mean }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.3.3/rxjs.umd.min.js"></script> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM