Rxjs merge 学习笔记

2021-08-04  本文已影响0人  华山令狐冲

官方链接: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 的所有值。

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));

输出:


另一个例子:

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

输出:


更多Jerry的原创文章,尽在:"汪子熙":


上一篇 下一篇

猜你喜欢

热点阅读