RxJS
的文档定义AsyncSubject
如下:
AsyncSubject是一种变体,只将Observable执行的最后一个值发送给它的观察者,并且只有在执行完成时才会发送。
我不知道在哪里/为什么我需要使用这个主题变体。有人可以提供解释或现实世界的例子来说明它存在的原因及其优势吗?
答案 0 :(得分:14)
看起来它对于获取和缓存(一次性)资源非常有用,因为http.get通常会发出一个响应然后完成。
来自rxjs/spec/subjects/AsyncSubject-spec.ts
它('完成时应该发出最后一个值',()=> {
它('在完成后订阅时应该发出最后一个值',()=> {
它('应该继续向后续订阅发送最后一个值',()=> {
获取后订阅的组件将获取值,而Subject
不是这种情况
const subject = new Rx.Subject();
const asyncSubject = new Rx.AsyncSubject();
// Subscribe before
subject.subscribe(x => console.log('before complete - subject', x))
asyncSubject.subscribe(x => console.log('before complete - asyncSubject', x))
subject.next('value 1');
subject.complete();
subject.next('value 2');
asyncSubject.next('value 1');
asyncSubject.complete();
asyncSubject.next('value 2');
// Subscribe after
subject.subscribe(x => console.log('after complete - subject', x))
asyncSubject.subscribe(x => console.log('after complete - asyncSubject', x))

.as-console-wrapper { max-height: 100% ! important; top: 0 }

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>
&#13;
答案 1 :(得分:0)
酷!
为了娱乐,我添加了处理程序以记录完成事件,以显示在主题完成后发生订阅时,无论在哪种情况下(Subject或AsyncSubject)它们都会引发。
还添加了BehaviorSubject。
const subject = new Rx.Subject();
const asyncSubject = new Rx.AsyncSubject();
const behaviorSubject = new Rx.BehaviorSubject();
console.log('before init - behaviorSubject', behaviorSubject.value)
subject.next('INIT');
asyncSubject.next('INIT');
behaviorSubject.next('INIT');
console.log('before subscribe - behaviorSubject', behaviorSubject.value)
// Subscribe before
subject.subscribe(x => console.log('before complete - subject', x))
asyncSubject.subscribe(x => console.log('before complete - asyncSubject', x))
behaviorSubject.subscribe(x => console.log('before complete - behaviorSubject', x))
subject.next('NEXT');
subject.complete();
asyncSubject.next('NEXT');
asyncSubject.complete();
behaviorSubject.next('NEXT');
behaviorSubject.complete();
// Subscribe after
subject.subscribe({
next: x => console.log('after complete - subject', x),
complete: () => console.log('after complete - subject COMPLETE')
})
asyncSubject.subscribe({
next: x => console.log('after complete - asyncSubject', x),
complete: () => console.log('after complete - asyncSubject COMPLETE')
})
behaviorSubject.subscribe({
next: x => console.log('after complete - behaviorSubject', x),
complete: () => console.log('after complete - behaviorSubject COMPLETE')
})
.as-console-wrapper { max-height: 100% ! important; top: 0 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>