toPromise() 是否取消订阅 Observable? [英] Does toPromise() unsubscribe from the Observable?

查看:96
本文介绍了toPromise() 是否取消订阅 Observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到任何规范文本来回答这个问题.我一直在使用这种代码模式(这是在 Angular 应用程序中的 TypeScript 中):

I have not been able to find any normative text to answer this question. I have been using this code pattern (this is in TypeScript in an Angular application):


observeSomethingFun$: Observable<Fun>;
    ...
async loadsOfFun() {
  const fun = await this.observeSomethingFun$.toPromise();
    // I now have fun
}

一般来说,Observables 需要取消订阅.当使用 Angular async 管道时会自动发生这种情况,但在这种情况下会发生什么?toPromise 是否在发出一个值后取消订阅?

In general, Observables need to be unsubscribed from. This happens automatically when the Angular async pipe is used but what happens in this case? Does toPromise unsubscribe after emitting one value?

如果没有,我如何手动取消订阅?

If not, how do I unsubscribe manually?

更新:

事实证明@Will Taylor 下面的回答是正确的,但我的问题需要澄清一下.

It turns out @Will Taylor's answer below is correct but my question needs some clarification.

在我的例子中,Observable 发出一个永无止境的流,这与 Angular 的 HttpClient Observable 不同,它在发出一个值后完成.所以就我而言,根据 Taylor 的回答,我永远不会通过 await 声明.

In my case the Observable emits a never-ending stream, unlike for example Angular's HttpClient Observables that complete after emitting one value. So in my case I would never get past the await statement according to Taylor's answer.

RxJS 使这个问题很容易解决.正确的说法是:

RxJS makes this easy to fix. The correct statement turns out to be:

const fun = await this.observeSomethingFun$.pipe(first()).toPromise();

RxJS first 运算符将接收第一个值并取消订阅源 Observable.然后它会将该值发送给 toPromise 操作符然后完成.

The RxJS first operator will receive the first value and unsubscribe from the source Observable. it will then send out that value to the toPromise operator and then complete.

推荐答案

无需退订.

这很方便,因为无法取消对承诺的订阅.

Which is convenient, as there is no way to unsubscribe from a promise.

  • 如果 Observable 完成 - 承诺将resolve 发出最后一个值,此时所有订阅者将自动取消订阅.

  • If the Observable completes - the promise will resolve with the last value emitted and all subscribers will automatically be unsubscribed at this point.

如果 Observable 错误 - 承诺将 reject 并且所有订阅者此时将自动取消订阅.

If the Observable errors - the promise will reject and all subscribers will automatically be unsubscribed at this point.

然而,toPromise 存在一些边缘情况,其中的行为从 文档.

However, there are a couple of edge cases with toPromise in which the behavior is not completely clear from the docs.

  1. 如果 Observable 发出一个或多个值但没有完成或出错,则承诺既不会解决也不会拒绝.在这种情况下,promise 会在内存中徘徊,这在使用 toPromise 时值得考虑.

如果 Observable 完成但没有发出值,promise 将 resolveundefined.

If the Observable completes but does not emit a value, the promise will resolve with undefined.

这篇关于toPromise() 是否取消订阅 Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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