是否有一种方法在订阅了一个可观察对象之后再添加一个元素?
observable = timer(1000,2000).take(5)
observable.subscribe()
//Now I want to add one more element to observable....
答案 0 :(得分:2)
也许您正在寻找一个主题,一个主题既可以观察又可以观察。
const { Subject, timer, fromEvent } = rxjs;
const { take } = rxjs.operators;
let subject$ = new Subject();
subject$.subscribe(val => { console.log(val); });
timer(1000,2000).pipe(take(5)).subscribe(val => { subject$.next(val); });
fromEvent(document.getElementsByTagName('button')[0], 'click').subscribe(() => {
subject$.next('clicked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>
<button>Click</button>
答案 1 :(得分:1)
const { Subject, timer, merge } = rxjs;
const { take } = rxjs.operators;
let source_1 = timer(1000,2000).pipe(take(5));
let source_2 = new Subject();
let final_source = merge(
source_1,
source_2
);
final_source.subscribe(e => console.log(e));
source_2.next('jabadabadoo!');
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>