问题
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.
回答1:
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)]);
Live demo: https://stackblitz.com/edit/rxjs-vmcqs9
来源:https://stackoverflow.com/questions/59916768/rxjs-dynamic-source-of-observables