Does toPromise() unsubscribe from the Observable?

淺唱寂寞╮ 提交于 2021-01-27 05:40:42

问题


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
}

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?

Update:

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

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 makes this easy to fix. The correct statement turns out to be:

const fun = await this.observeSomethingFun$.pipe(first()).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.


回答1:


No need to unsubscribe.

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

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

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

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

  1. If the Observable emits one or more values but does not complete or error, the promise will neither resolve or reject. In this case, the promise would hang around in memory, which is worth considering when working with toPromise.

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



来源:https://stackoverflow.com/questions/59402377/does-topromise-unsubscribe-from-the-observable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!