
RxJS是一組可以用來處理非同步、以及同步事件的一個JavaScript Library
能幫助你快速地使用像是Ajax、Server Work、SetTimeout 等其他非同步的事件
而它主要可以分為兩大類:
之前在討論的 Zone.js 時提到
傳統上我們在使用非同步的時候,會需要確保我們的程式執行順序不會被打亂
因此在非同步的程式開發上,我們多半會採用 CallBack Function來解決問題,讓我們執行順序能正常Work
但是有些情況下你可能很常會遇到一些特殊的需求:
我需要先發送一個非同步的請求來處理使用者的資料,接著在資料回傳後使用者操作過後,又再發一個請求給Server
這時候我們的程式就會透過CallBack Function來幫助我們發送第二個請求
export class HomeComponent implements OnInit, OnDestroy {
  private firstSubscription: Subscription;
  constructor() { }
  ngOnInit() {
    this.firstSubscription = interval(1000).subscribe(count => {
      console.log(count);
    });
  }
  ngOnDestroy() {
    this.firstSubscription.unsubscribe();
  }
}
除了使用 rxjs 內建的方法外, 還可以針對需求撰寫自己需要的 Rxjs
export class HomeComponent implements OnInit, OnDestroy {
  private firstSubscription: Subscription;
  constructor() { }
  ngOnInit() {
    this.firstSubscription = interval(1000).subscribe(count => {
      console.log(count);
    });
    const customIntervalObservable = Observable.create(observer => {
      let count = 0;
      setInterval(() => {
        observer.next(count);
        if (count === 2) {
          observer.complete();
        }
        if (count > 3) {
          observer.error(new Error('Count is greater 3'));
        }
        count++;
      }, 1000);
    });
    this.firstSubscription = customIntervalObservable.subscribe(data => {
      console.log(data);
    }, error => {
      console.log(error);
    });
  }
  ngOnDestroy() {
    this.firstSubscription.unsubscribe();
  }
}
上面的範例建立了一個 Observable,建立了每一秒顯示在 Console