RXJS中的AsyncSubject有什么意义? [英] What's the point of AsyncSubject in RXJS?

查看:66
本文介绍了RXJS中的AsyncSubject有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

RxJS的文档对AsyncSubject的定义如下:

The documentation for RxJS defines AsyncSubject as follows:

AsyncSubject是一种变体,其中只有Observable执行的最后一个值发送到其观察者,并且仅在执行完成时发送.

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.

我不知道在哪里/为什么我需要使用此主题的变体.有人可以提供一个解释或一个真实的例子来说明它为什么存在及其优点吗?

I don't see where / why I would ever need to use this variant of subject. Can someone provide an explanation or a real-world example to illustrate why it exists and its advantages?

推荐答案

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

It looks like it could be useful for fetching and caching (one-shot) resources, since generally http.get will emit one response then complete.

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

it('完成时应发出最后一个值',()=> {
它(完成后订阅时应发出最后一个值",()=> {
它(应继续向后续订阅发送最后一个值",()=> {

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则不是这种情况.

Components that subscribe after the fetch will then pick up value, which is not the case for 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中的AsyncSubject有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆