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

查看:20
本文介绍了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/.ts

it('完成时应该发出最后一个值', () => {
it('订阅完成后应该发出最后一个值', () => {
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天全站免登陆