我的一个 Observable.combineLatest
永远不会完成,因为它的一个 observable 永远不会发出值,所以永远不会达到完成功能。
有没有办法让我可以设置一种timeOut
,然后我可以为它提供一个默认值?或者至少是一种判断哪个可观察对象根本没有发出任何数据的方法?
有点像
Observable.combineLatest(...).onTimeOut(() => console.log('No data from 3th observable')
编辑:
鉴于此:
Observable.combineLatest(
observable1, // <- ok
observable2, // <- ok
observable3, // <- timeout
observable4, // <- ok
observable5, // <- ok
(...args) => ({...args})
)
.pipe(
timeout(1*1000),
catchError((e) => {
console.log(e)
return Observable.of({})
})
)
.subscribe(() => {})
我怎么知道 observable3 是造成超时的原因?
最佳答案
您可以使用 timeout和 catchError此用例的运算符(或只是 timeoutWith ,请参阅下面的编辑):
combineLatest(...).pipe(
timeout(myTimeoutValueInMilliseconds),
// Catch the error thrown by the timeout and return a default value instead.
catchError(() => of('my default value'))
).subscribe(e => console.log(e))
当然,如果你只需要一个 Observables 的超时,那么你可以按如下方式重组它:
combineLatest(
myObsOne.pipe(
timeout(myTimeoutValueInMilliseconds),
catchError(() => of('my default value'))
),
myObsTwo
).subscribe(e => console.log(e))
编辑
正如 Oles Savluk 在评论中指出的那样,您可以使用 timoutWith 来简化此解决方案。而不是 timeout
和 catchError
:
combineLatest(
myObsOne.pipe(
timeoutWith(myTimeoutValueInMilliseconds, of('my default value')),
),
myObsTwo
).subscribe(e => console.log(e))
关于javascript - RxJS Observable.combineLatest 永远不会完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58098493/