Thursday, 22 June 2017

javascript - How can I `await` on an Rx Observable?



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 usecase 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.


Answer



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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...