1. 程式人生 > >RxJS學習筆記之Subject

RxJS學習筆記之Subject

原創 謝謝 AR clas .com avi sync complete 數據

本文為原創文章,轉載請標明出處

目錄

  1. Subject
  2. BehaviorSubject
  3. ReplaySubject
  4. AsyncSubject

1. Subject

總的來說,Subject 既是能夠將值多播給多個觀察者的特殊的可觀察對象,因為可以添加觀察者並使用 subscribe 方法來接收值;又是觀察者,因為它有 next(v)error(e)complete() 方法。下面這段代碼很好的說明了每個 Subject 既是 Observable 又是 Observer

var subject = new Rx.Subject();

subject.subscribe({
  next: (v) => console.log(‘observerA: ‘ + v)
});
subject.subscribe({
  next: (v) => console.log(‘observerB: ‘ + v)
});

subject.next(1);
subject.next(2);

輸出:

observerA: 1
observerB: 1
observerA: 2
observerB: 2

2. BehaviorSubject

BehaviorSubject 能夠保存當前值,當有新的觀察者訂閱時,就會立即從BehaviorSubject 接收到當前值。下面這段代碼,初始值為0,盡管第二個觀察者是在 2 發送出去之後訂閱的,但是BehaviorSubject 保存了當前值,在第二個觀察者訂閱時立即從BehaviorSubject 接收到了當前值 2

var subject = new Rx.BehaviorSubject(0);

subject.subscribe({
  next: (v) => console.log(‘observerA: ‘ + v)
});

subject.next(1);
subject.next(2);

subject.subscribe({
  next: (v) => console.log(‘observerB: ‘ + v)
});

subject.next(3);

輸出:

observerA: 0
observerA: 1
observerA: 2
observerB: 2
observerA: 3
observerB: 3

3. ReplaySubject

ReplaySubjectBehaviorSubject 相似,ReplaySubject 能夠保存指定個數的數據,當有新的觀察者訂閱時,就會從 ReplaySubject 接收到指定個數的這些值並回放出來。下面這段代碼,指定能夠保存 3 個數據,當第二個觀察者訂閱時,獲取到保存的三個值 234

var subject = new Rx.ReplaySubject(3); 

subject.subscribe({
  next: (v) => console.log(‘observerA: ‘ + v)
});

subject.next(1);
subject.next(2);
subject.next(3);
subject.next(4);

subject.subscribe({
  next: (v) => console.log(‘observerB: ‘ + v)
});

subject.next(5);

輸出:

observerA: 1
observerA: 2
observerA: 3
observerA: 4
observerB: 2
observerB: 3
observerB: 4
observerA: 5
observerB: 5

另外,ReplaySubject 還可以指定 windowTime 來保存到目前為止多久之內的數據,下面這段代碼,指定能夠保存 100 個數據,指定能夠保存到目前為止 500 毫秒之內的數據。

var subject = new Rx.ReplaySubject(100, 500);

subject.subscribe({
  next: (v) => console.log(‘observerA: ‘ + v)
});

var i = 1;
setInterval(() => subject.next(i++), 200);

setTimeout(() => {
  subject.subscribe({
    next: (v) => console.log(‘observerB: ‘ + v)
  });
}, 1000);

輸出:

observerA: 1
observerA: 2
observerA: 3
observerA: 4
observerA: 5
observerB: 3
observerB: 4
observerB: 5
observerA: 6
observerB: 6
...

4. AsyncSubject

AsyncSubject 只能將執行完成時的最後一個值發送給觀察者。下面這段代碼,當 complete() 時才會將最後一個值 5 發送給第一個觀察者和第二個觀察者。

var subject = new Rx.AsyncSubject();

subject.subscribe({
  next: (v) => console.log(‘observerA: ‘ + v)
});

subject.next(1);
subject.next(2);
subject.next(3);
subject.next(4);

subject.subscribe({
  next: (v) => console.log(‘observerB: ‘ + v)
});

subject.next(5);
subject.complete();

輸出:

observerA: 5
observerB: 5

如有不當之處,請予指正,謝謝~

RxJS學習筆記之Subject