How can I `await` on an Rx Observable?
Use the new firstValueFrom()
or lastValueFrom()
instead of toPromise()
, which as pointed out here, is deprecated starting in RxJS 7, and will be removed in RxJS 8.
import { firstValueFrom} from 'rxjs';
import { lastValueFrom } from 'rxjs';
this.myProp = await firstValueFrom(myObservable$);
this.myProp = await lastValueFrom(myObservable$);
This is available in RxJS 7+
See: https://indepth.dev/rxjs-heads-up-topromise-is-being-deprecated/
You have to pass a promise to await
. Convert the observable's next event to a promise and await that.
if (condition) {
await observable.first().toPromise();
}
Edit note: This answer originally used .take(1) but was changed to use .first() which avoids the issue of the Promise never resolving if the stream ends before a value comes through.
As of RxJS v8, toPromise
will be removed. Instead, the above can be replaced with await firstValueFrom(observable)