Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  45] [ 3]  / answers: 1 / hits: 161097  / 9 Years ago, wed, december 9, 2015, 12:00:00

I'd like to be able to await on an observable, e.g.



const source = Rx.Observable.create(/* ... */)
//...
await source;


A naive attempt results in the await resolving immediately and not blocking execution



Edit:
The pseudocode for my full intended use case is:



if (condition) {
await observable;
}
// a bunch of other code


I understand that I can move the other code into another separate function and pass it into the subscribe callback, but I'm hoping to be able to avoid that.


More From » rxjs

 Answers
5

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)


[#64115] Monday, December 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rashawn

Total Points: 451
Total Questions: 83
Total Answers: 83

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
;