Reputation: 268
Sometimes subscribing in a component, rather than using an async pipe is needed.
In these cases when only one value will ever be emitted by the observable, is there any reason or downside to converting to a promise? Since we are not subscribing, wouldn't this be safer than possibly having a memory leak if someone doesn't unsubscribe?
Upvotes: 2
Views: 614
Reputation: 4502
The downside I am aware of is that toPromise()
is going to be deprecated in rxjs 7 and removed in rxjs 8. If you use it a lot now it will require extra work to migrate later. If you want have your code future proof in 6.x, implement lastValueFrom and firstValueFrom now, and use them, then it would be easy later to change the implementation provided in rxjs7 and removing those two methods. See the linked article for their usage.
import { Observable } from 'rxjs';
import { first } from 'rxjs/operators';
export function lastValueFrom<T>(obs$: Observable<T>): Promise<T> {
return obs$.toPromise();
}
export function firstValueFrom<T>(obs$: Observable<T>): Promise<T> {
return obs$.pipe(first()).toPromise();
}
Upvotes: 3