仅当 returns 比延迟快时,我如何才能延迟可观察对象
How can I delay an observable only if it returns faster than the delay
举个例子:
this.http.get('/getdata').pipe(delay(2000))
我希望此请求至少需要 2 秒才能完成,但不会超过请求完成所需的时间。
换句话说:
如果请求需要 1s 完成,我希望 observable 在 2s.[=13 内完成=]
如果请求需要 3s 完成,我希望 observable 在 3s 内完成,而不是 5s.
是否有除 delay()
之外的其他管道可以实现我不知道的这一点,或者是否有必要在必要时为此构建自定义管道?
用例是显示一个加载器,但是如果请求完成得太快,当加载器只是 "flashes" 瞬间
时看起来不太好
要回答所问的问题,您可以简单地使用 combineLatest()
将 timer(2000)
observable 和 request observable 组合起来,然后忽略计时器 observable 的结果。它之所以有效,是因为 combineLatest
等到所有 observable 都至少发出一个值,然后再发出一个值。
combineLatest(this.http.get('/getdata'), timer(2000), x => x)
感谢 GregL,我将其更新为仅使用 forkJoin。这将获得流的最新值。但是如果你想在每次发射时检查它,你可以用 combineLatest 替换 forkJoin ,这也可以。
在我的工作示例中:
this.ibanSubscription = forkJoin({
iban: this.ibantobicService.getById(Iban),
timer: timer(1000) //so now the ajax call will take at least 1 second
}
).pipe(
map( (stream: any) => <BicModel>stream.iban),
switchMap( (bic: BicModel) => of(this.processIbanData(bic))),
catchError((error: any) => of(this.messageList.handleError(error))),
finalize(() => this.loadIbanToBicFinalize())
).subscribe();
举个例子:
this.http.get('/getdata').pipe(delay(2000))
我希望此请求至少需要 2 秒才能完成,但不会超过请求完成所需的时间。
换句话说:
如果请求需要 1s 完成,我希望 observable 在 2s.[=13 内完成=]
如果请求需要 3s 完成,我希望 observable 在 3s 内完成,而不是 5s.
是否有除 delay()
之外的其他管道可以实现我不知道的这一点,或者是否有必要在必要时为此构建自定义管道?
用例是显示一个加载器,但是如果请求完成得太快,当加载器只是 "flashes" 瞬间
时看起来不太好要回答所问的问题,您可以简单地使用 combineLatest()
将 timer(2000)
observable 和 request observable 组合起来,然后忽略计时器 observable 的结果。它之所以有效,是因为 combineLatest
等到所有 observable 都至少发出一个值,然后再发出一个值。
combineLatest(this.http.get('/getdata'), timer(2000), x => x)
感谢 GregL,我将其更新为仅使用 forkJoin。这将获得流的最新值。但是如果你想在每次发射时检查它,你可以用 combineLatest 替换 forkJoin ,这也可以。 在我的工作示例中:
this.ibanSubscription = forkJoin({
iban: this.ibantobicService.getById(Iban),
timer: timer(1000) //so now the ajax call will take at least 1 second
}
).pipe(
map( (stream: any) => <BicModel>stream.iban),
switchMap( (bic: BicModel) => of(this.processIbanData(bic))),
catchError((error: any) => of(this.messageList.handleError(error))),
finalize(() => this.loadIbanToBicFinalize())
).subscribe();