[RxJS] Convert RxJS Subjects to Observables

The use of RxJS Subjects is common, but not without problems. In this lesson we will see how they can be usually safely replaced with plain Observables.

 

Check the follow code:

const click$ = new Rx.Subject();

document.addEventListener('click', function(e) {
  click$.next(e)
});

click$.subscribe(function(v) {
  console.log(v)
});

 

One problem for this is that 'click$' become a global variable, not easy for maintance. 

Not so sure how it will impact Angular, because Angular use component anyway, the subject only available to the component, maybe have low impact. 

But let's see if you are not using Angular, how to conver a Subject to Observable.

const click$ = Rx.Observable.create(function(observer) {
  const handler = (e) => {
    observer.next(e)
  };
  
  document.addEventListener('click', handler);
  
  return function unsubscribe(){
    document.removeEventListener('click', handler)
  }

});


const subscription = click$.subscribe(function (ev) {
  console.log(ev.clientX);
});

setTimeout(function () {
  subscription.unsubscribe();
}, 2000);

 

posted @ 2017-05-26 19:16  Zhentiw  阅读(190)  评论(0编辑  收藏  举报