rxjs 超时到第一个值 [英] rxjs timeout to first value

查看:56
本文介绍了rxjs 超时到第一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我从 这个问题 中了解到,timeout 如果 observable 在给定的时间窗口内没有发出任何值,则会出现运算符错误......对我来说问题是,这个时间窗口在每次发出后都会重置,如果你仅对第一个值在窗口内发出时感兴趣...

so as I understood from this question here I understood that timeout operator errors if an observable does not emit any value in the given window of time... the problem for me is, that this window of time resets after each emit, making it necessary to complete the sequence if you are only interested if the first value(s) emit within the window...

有没有一种先超时"的好方法?除了 .take(1).timeout(1000)?

is there a nice way to have a "timeout to first"? Other than .take(1).timeout(1000)?

推荐答案

除了@Maxime 的回答,你还可以使用 race 在您的 observable 的第一个值和超时之间创建竞争.我们通过结合 nevertimeout 来构造超时.

In addition to @Maxime's answer, you can use race to create a race between your observable's first value and a timeout. We construct the timeout by combining never with timeout.

因此,我们最终会在源 observable 和永远不会发出值但会在时间过去后抛出错误的 observable 之间进行竞争.如果源 observable 产生它的第一个值,那么 race 将停止监听超时 observable.

Thus we end up with a race between your source observable, and an observable that will never emit a value, but will throw an error after time goes by. If your source observable produces its first value, then race will stop listening to the timeout observable.

const timed = source.race(Observable.never().timeout(1000));

这篇关于rxjs 超时到第一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆