zoukankan      html  css  js  c++  java
  • [RxJS] Creating Observable From Scratch

    Get a better understanding of the RxJS Observable by implementing one that's similar from the ground up.

    class SafeObserver {
      constructor(destination) {
        this.destination = destination;
      }
      
      next(value) {
        const destination = this.destination;
        if (destination.next && !this.isUnsubscribed) {
          destination.next && destination.next(value);
        }
      }
      
      error(err) {
        const destination = this.destination;
        if (!this.isUnsubscribed) {
          if (destination.error) {
            destination.error(error);
          }
          this.unsubscribe();
        }
      }
      
      complete() {
        const destination = this.destination;
        if (!this.isUnsubscribed) {
          if (destination.complete) {
            destination.complete();
          }
          this.unsubscribe();
        }
      }
      
      unsubscribe() {
        this.isUnsubscribed = true;
        if (this._unsubscribe) {
          this._unsubscribe();
        }
      }
    }
    
    class Observable {
      constructor(_subscribe) {
        this._subscribe = _subscribe;
      }
      
      subscribe(observer) {
        const safeObserver = new SafeObserver(observer);
        safeObserver._unsubscribe = this._subscribe(safeObserver);
        return () => safeObserver.unsubscribe();
      }
    }
    
    const myObservable = new Observable((observer) => {
      let i = 0;
      const id = setInterval(() => {
        if (i < 10) {
          observer.next(i++);
        } else {
          observer.complete();
        }
      }, 100);
      
      return () => {
        console.log('unsubbed');
        clearInterval(id);
      };
    });
    
    const observer = {
      next(value) { console.log('next -> ' + value); },
      error(err) { },
      complete() { console.log('complete'); }
    };
    
    
    const foo = myObservable.subscribe(observer);
    
    foo.unsubscribe();
  • 相关阅读:
    svn提交时强制添加注释 (转)
    通过IIS调试ASP.NET项目
    当前标识(IIS APPPOOLDefaultWebSite)没有对“C:WindowsMicrosoft.NETFramework64v2.0.50727Temporary ASP.NET Files“的写访问权限
    (转)WPF控件开源资源
    redhat7系统安装kerberos报错
    centos7
    spark-sql与Hive元数据共享
    hive-llap配置
    spark-二次排序
    kylin3.1基于ambari2.7.5部署总结
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5285918.html
Copyright © 2011-2022 走看看