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);
  • 相关阅读:
    lists 函数整理
    orddict 练习
    github 的使用
    wxListCtrl 例子 二
    Erlang eunit
    Erlang 中 Tuple 使用 以及 List 模块意外
    Erlang Json
    模块和包
    Mysql作为zabbix数据库ibdata1文件太高解决
    用户管理和数据库安全
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6910122.html
Copyright © 2011-2022 走看看