Paolo
Paolo

Reputation: 2472

RxJS Add an observable after subscribe

Is there a way to add one more element after an observable has been subscribed?

observable = timer(1000,2000).take(5)
observable.subscribe()
//Now I want to add one more element to observable....

Upvotes: 0

Views: 2779

Answers (2)

Jonathan Stellwag
Jonathan Stellwag

Reputation: 4287

You can use a combination of merge and Subjects

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>

Upvotes: 1

Adrian Brand
Adrian Brand

Reputation: 21658

Maybe a subject is what you are looking for, a subject is both an observable and an observer.

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>

Upvotes: 2

Related Questions