关于RxJS Subject的学习笔记(8)

AsyncSubject 应用

AsyncSubject 类似于 last 操作符,它会在 Subject 结束后发出最后一个值,具体示例如下:

var subject = new Rx.AsyncSubject();

 var observerA = {
  next: value => console.log('Observer A get value: ' + value),
  error: error => console.log('Observer A error: ' + error),
  complete: () => console.log('Observer A complete!')
 };

 var observerB = {
  next: value => console.log('Observer B get value: ' + value),
  error: error => console.log('Observer B error: ' + error),
  complete: () => console.log('Observer B complete!')
 };

 subject.subscribe(observerA);

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

 subject.complete();

 setTimeout(() => {
  subject.subscribe(observerB); // 1秒后订阅
 }, 1000);

以上代码运行后,控制台的输出结果:

Observer A get value: 3
Observer A complete!
Observer B get value: 3
Observer B complete!

JSBin - AsyncSubject

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。