RxJS 动态观察源 [英] RxJS dynamic source of observables

查看:50
本文介绍了RxJS 动态观察源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含许多 observable 的 Observable(合并它们).这可以通过 merge(...arrayOfObservables) 实现.问题是这个数组会在一段时间内改变,而 observable 也应该订阅新的 observable.

I want to create an Observable of many observables (merge them). This could be achieved with merge(...arrayOfObservables). The problem is that some time this array will be changed and the observable should subscribe to the new observables, too.

推荐答案

您可以将新的 Observable 推送到一个数组,然后发出该数组并使用 switchMap 订阅它们.

You can push new Observables to an array and then emit the array and subscribe to them with switchMap.

import { of, merge, BehaviorSubject } from 'rxjs'; 
import { switchMap } from 'rxjs/operators';

const s = new BehaviorSubject([of(1), of(2), of(3)]);

s.pipe(
  switchMap(array => merge(...array)),
).subscribe(x => console.log(x));

s.next([...s.getValue(), of(4)]);

现场演示:https://stackblitz.com/edit/rxjs-vmcqs9

这篇关于RxJS 动态观察源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆