zoukankan      html  css  js  c++  java
  • [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);
  • 相关阅读:
    indexOf--之美
    uniapp_切换主题
    ueditor调用其中的附件上传功能
    php7 编译安装 apache
    快速排序单循环
    插入排序
    走进svg
    phpstorm内网远程debug
    sass&compass&grunt
    centos7+nginx 1.9.0+php-fpm+phpstorm+xdebug+vmware开发环境搭建
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6910122.html
Copyright © 2011-2022 走看看