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);
  • 相关阅读:
    高德地图SDK大致使用
    AFNetworking 使用
    蓝牙相关
    svn 常用命令
    通过AutoLayout显示三个等宽视图
    适配相关 --AutoLayout ---SizeClass
    常用网页
    UIViewController加载过程
    UIApplication相关
    实现消息转发功能(调用非自己类方法)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6910122.html
Copyright © 2011-2022 走看看