I am confused about what the purpose of the "dispose" or "unsubscribe" function is for, which is (optionally) returned from an observable "executor" function, like so:
const Rx = require('rxjs');
const obs = Rx.Observable.create(obs => {
// we are in the Observable "executor" function
obs.next(4);
// we return this function, which gets called if we unsubscribe
return function () {
console.log('disposed');
}
});
const s1 = obs.subscribe(
function (v) {
console.log(v);
},
function (e) {
console.log(e);
},
function () {
console.log('complete');
}
);
const s2 = obs.subscribe(
function (v) {
console.log(v);
},
function (e) {
console.log(e);
},
function () {
console.log('complete');
}
);
s1.unsubscribe();
s2.unsubscribe();
What confuses me is that such a function would actually be more likely to hold on to references in your code and therefore prevent garbage collection.
Can anyone tell me what the purpose is of returning a function in that scenario, what the function is called, and what it's signature is? I am having trouble figuring out information about it.
I also see much more complex examples of returning a subscription from the executor function, for example this:
let index = 0;
let obsEnqueue = this.obsEnqueue = new Rx.Subject();
this.queueStream = Rx.Observable.create(obs => {
const push = Rx.Subscriber.create(v => {
if ((index % obsEnqueue.observers.length) === obsEnqueue.observers.indexOf(push)) {
obs.next(v);
}
});
return obsEnqueue.subscribe(push);
});
This seems to return a subscription instead of just a plain function. Can anyone explain what's going on with this?
To make it a clear question, what is the difference between doing this:
const sub = new Rx.Subject();
const obs = Rx.Observable.create($obs => {
$obs.next(4);
return sub.subscribe($obs);
});
and not returning the result of the subscribe call:
const sub = new Rx.Subject();
const obs = Rx.Observable.create($obs => {
$obs.next(4);
sub.subscribe($obs);
});