[RxJS] Creating Observable From Scratch

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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();

 

以上是关于[RxJS] Creating Observable From Scratch的主要内容,如果未能解决你的问题,请参考以下文章

[RxJS] Error handling operator: catch

Angular RxJS入门笔记 (Observable可观察对象Subscribe订阅Observer观察者Subscription对象)

rxjs 入门--环境配置

TypeScript - 等待 observable/promise 完成,然后返回 observable

html 使用AJAX POST请求来调用控制器操作(在页面加载时和在下拉列表中选择项目时),获取返回的布尔值,设置observabl

如何理解 RxJS?RxJS的中文API和使用教程