天天看點

Rxjs merge 學習筆記

官方連結: https://rxjs-dev.firebaseapp.com/api/index/function/merge

Creates an output Observable which concurrently emits all values from every given input Observable.

建立一個輸出 Observable,它同時發出來自每個給定輸入 Observable 的所有值。

Rxjs merge 學習筆記

merge subscribes to each given input Observable (as arguments), and simply forwards (without doing any transformation) all the values from all the input Observables to the output Observable. The output Observable only completes once all input Observables have completed. Any error delivered by an input Observable will be immediately emitted on the output Observable.

merge 訂閱每個給定的輸入 Observable(作為參數),并簡單地将所有輸入 Observable 的所有值(不做任何轉換)轉發到輸出 Observable。 輸出 Observable 僅在所有輸入 Observable 完成後才完成。 輸入 Observable 傳遞的任何錯誤都将立即在輸出 Observable 上發出。

看一個例子:

import { merge, fromEvent, interval } from 'rxjs';
 
const clicks = fromEvent(document, 'click');
const timer = interval(1000);
const clicksOrTimer = merge(clicks, timer);
clicksOrTimer.subscribe(x => console.log(x));
      

輸出:

Rxjs merge 學習筆記

另一個例子:

import { merge, interval } from 'rxjs';
import { take } from 'rxjs/operators';
 
const timer1 = interval(1000).pipe(take(10));
const timer2 = interval(2000).pipe(take(6));
const timer3 = interval(500).pipe(take(10));
const concurrent = 2; // the argument
const merged = merge(timer1, timer2, timer3, concurrent);
merged.subscribe(x => console.log(x));
 
// Results in the following:
// - First timer1 and timer2 will run concurrently
// - timer1 will emit a value every 1000ms for 10 iterations
// - timer2 will emit a value every 2000ms for 6 iterations
// - after timer1 hits its max iteration, timer2 will
//   continue, and timer3 will start to run concurrently with timer2
// - when timer2 hits its max iteration it terminates, and
//   timer3 will continue to emit a value every 500ms until it is complete
      
Rxjs merge 學習筆記

繼續閱讀