8
votes

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
What language is that?user12211554
@Asadefa As it says: Typescript. But it might as well be just JavascriptAlanObject
Ok then so it is Typescript. I don't know Typescript so sorry I can't help.user12211554
The promise resolves when the source observable completes or errors - in which case, automatic unsubscription occurs.cartant

1 Answers

6
votes

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.