码迷,mamicode.com
首页 > Web开发 > 详细

[RxJS] Creating Observable From Scratch

时间:2016-03-17 07:06:13      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5285918.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!