Reputation: 34099
I have a connectable observable that will get connected, when the other stream executed:
const source1 = Rx.Observable.of([1,2,3,4,5])
.do(() => console.log('Do Something!'))
.map(() => "Always connected.")
.publish();
source1.subscribe((v) => console.log(v));
const connect = () => {
let c = false;
return () => {
if (!c) {
console.log("Get connected");
source1.connect();
c = true;
}
}
}
const source2 = Rx.Observable.fromEvent(document, 'click')
.do(() => console.log("execute!"))
.do(connect())
.switchMapTo(source1);
source2.subscribe((v) => console.log(v));
The output
"execute!"
"Get connected"
"Do Something!"
"Always connected."
Further clicks on the document source1
will be not subscribe anymore and my question is, why?
Upvotes: 2
Views: 293
Reputation: 96949
You've encountered exactly this situations: Rx.Subject loses events
If you update the first part of your example you'll see that the Subject receives a complete
notification:
const source1 = Rx.Observable.of([1,2,3,4,5])
.do(() => console.log('Do Something!'), null, () => console.log('source1 complete'))
.map(() => "Always connected.")
.publish();
This marks that Subject as closed and it won't reemit any values ant further.
See my linked answer above for more detailed information. Also you might have a look at On The Subject Of Subjects (in RxJS) (paragramp Subjects Are Not Reusable) by Ben Leash (lead developer of RxJS 5.
Upvotes: 1