Search code examples
javascriptrxjsobservable

How can I `await` on an Rx Observable to have a specific value?


I'd like to await an observable to have a define value before moving forward.

I tried the follwoing, but it is not working, even if myObservable$ is instantiated with a value

await lastValueFrom(this.myObservable$.pipe(filter((event) => (event == 'something' ? true : false))))

Context

In angular, while loading the app inside an iFrame, I need a token that may exists locally or being set by the parent.

If this is set by the parent, I would like my guard to await till the token has been value.

Workaround

I've create an observable only for this purpose, so I could use the await lastValueFrom(this.myObservable$) and this is working, but I'm just wondering if it was possible to await a specific value.


Solution

  • In order for lastValueFrom to emit anything, its observable source must complete (otherwise, there is no "last" value).

    You can force it to complete by using take(1) after your filter condiation:

    await lastValueFrom(this.myObservable$.pipe(
        filter(event => event === 'something'),
        take(1)
    ));