我如何在 Rx Observable 上“等待"?

编程入门 行业动态 更新时间:2024-10-28 12:26:35
本文介绍了我如何在 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

我的完整预期用例的伪代码是:

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.

推荐答案

您必须将承诺传递给 await.将 observable 的下一个事件转换为 promise 并等待它.

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();
}

编辑注意:此答案最初使用 .take(1) 但已更改为使用 .first() 避免了如果流在值通过之前结束则无法解决 Promise 的问题.

从 RxJS v8 开始,toPromise 将被移除.相反,上述内容可以替换为 await firstValueFrom(observable)

As of RxJS v8, toPromise will be removed. Instead, the above can be replaced with await firstValueFrom(observable)

这篇关于我如何在 Rx Observable 上“等待"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 23:10:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/709827.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Rx   quot   Observable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!