[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');
  }, 1000);
  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();  
}, 4500);

 

posted @ 2016-04-17 23:36  Zhentiw  阅读(189)  评论(0)    收藏  举报