[RxJS] Returning subscriptions from the subscribe function

时间:2023-03-09 06:17:49
[RxJS] Returning subscriptions from the subscribe function

So far, when writing these subscribe functions, we haven't returned anything. It is possible return an unsubscribe function from a subscribe function. In this lesson we will see how to allow observers to subscribe and unsubscribe from an Observable.

var foo = new Rx.Observable(function subscribe(observer) {
var id = setInterval(function () {
observer.next('hi');
}, );
return function unsubscribe() {
clearInterval(id);
};
}); var subscription = foo.subscribe({
next: function (x) { console.log('next ' + x); },
error: function (err) { console.log('error ' + err); },
complete: function () { console.log('done'); },
}); setTimeout(function () {
subscription.unsubscribe();
}, );