How can I `await` on an Rx Observable?

心不动则不痛 提交于 2019-11-26 19:13:34

问题


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.


回答1:


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.




回答2:


It has to be

await observable.first().toPromise();

As it was noted in comments before, there is substantial difference between take(1) and first() operators when there is empty completed observable.

Observable.empty().first().toPromise() will result in rejection with EmptyError that can be handled accordingly, which is generally a desirable behaviour.

And Observable.empty().take(1).toPromise() will result in pending promise, which is desirable... almost never.




回答3:


You will need to await a promise, so you will want to use toPromise(). See this for more details on toPromise().



来源:https://stackoverflow.com/questions/34190375/how-can-i-await-on-an-rx-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!