问题
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.
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
.If the Observable completes but does not emit a value, the promise will
resolve
withundefined
.
来源:https://stackoverflow.com/questions/59402377/does-topromise-unsubscribe-from-the-observable