quanwei li
quanwei li

Reputation: 359

How create never complete subject of rxjs

friends. I get a Subject c, by dynamic subscribe from other observable object. but want when all observable complete then c complete without the first complete.

How can I do this ?

const c = new Subject;

const a = Observable.interval(100).take(3).mapTo('a');
const b = Observable.interval(150).take(3).mapTo('b');


a.subscribe(c);
b.subscribe(c);
c.subscribe(console.log);

real output

a
b
a
a

expect

a
b
a
a
b
b

Upvotes: 1

Views: 394

Answers (1)

martin
martin

Reputation: 96899

This is correct behavior because a Subject has an internal state and when it receives the complete notification it marks itself as "stopped" and will never ever emit anything. And that's exactly what's happening in you example. When you use a.subscribe(c) you're subscribing c to all three types of notifications and when the source emits complete it's received by c as well and it stops emitting.

Instead you can subscribe c only to next notifications:

a.subscribe(v => c.next(v));
b.subscribe(v => c.next(v));

Then if you want the source to properly complete when all sources complete you could do the following (you also need to use share() on all source Observables):

const a = Observable.interval(100)...share();
const b = Observable.interval(150)...share();

...

Observable.forkJoin(a, b)
  .subscribe(() => c.complete());

Upvotes: 1

Related Questions