I use the async
pipe in Angular, or takeUntil(...)
on components using:
export class BaseComponent implements OnDestroy {
ngUnsubscribe = new Subject<void>();
ngOnDestroy(): void {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
But, I've always wondered what I need to do when using from(myPromise)
. Promises only provide a single result, but I've converted it to an observable so it feels like if I make an equivalent method that provides an observable instead that I should be using take(1)
or unsubscribing depending on use since I don't always subscribe directly and instead use it in an exhaustMap(() => this.hasTokenExpired$()
.
public async hasTokenExpired(): Promise<boolean> {
const token = await this.getToken();
if (token) {
return this.jwtHelper.isTokenExpired(token);
}
return true;
}
// Observable equivalent method:
public hasTokenExpired$(): Observable<boolean> {
return from(this.hasTokenExpired()); // Could pipe `take(1)` permanently
}
Should I being using take(1)
on from(myPromise)
? It's been on my mind for awhile in case this causes a memory leak, but I can't find an article confirming that I should.
Also, if there's a better way to make these kinds of observable equivalent methods I'm always open to suggestions.
You never need to use take
in this case, as an Observable created from a Promise will only ever either:
This answer may be helpful to read too: Does toPromise() unsubscribe from the Observable?