gpt4 book ai didi

rxjs - RXJS 中的 AsyncSubject 有什么意义?

转载 作者:行者123 更新时间:2023-12-04 00:51:34 27 4
gpt4 key购买 nike

RxJS 的文档定义 AsyncSubject如下:

The AsyncSubject is a variant where only the last value of the Observable execution is sent to its observers, and only when the execution completes.



我不明白在哪里/为什么我需要使用这个主题变体。有人可以提供一个解释或一个真实世界的例子来说明它为什么存在和它的优点吗?

最佳答案

看起来它对于获取和缓存(一次性)资源很有用,因为通常 http.get 会发出一个响应然后完成。

来自 rxjs/spec/subjects/AsyncSubject-spec.ts

it('should emit the last value when complete', () => {
it('should emit the last value when subscribing after complete', () => {
it('should keep emitting the last value to subsequent subscriptions', () => {



获取后订阅的组件将获取值,而 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>

关于rxjs - RXJS 中的 AsyncSubject 有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306877/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com