[英]Observable polling in RxJs 6
Just wanted to migrate some of my legacy code to a newer version of RxJs.只是想将我的一些遗留代码迁移到较新版本的 RxJs。 The code was used for polling:该代码用于轮询:
Observable
.interval(5000)
.startWith(0)
.switchMap(() => this.apiService.getData())
.subscribe(data => /* ... */)
This worked fine in RxJs 5.2.0
.这在 RxJs 5.2.0
运行良好。
In RxJs 6.0.0
this doesn't work for multiple reasons ( Observable
only method is create
, interval
seems to be static, no method chaining, ...).在 RxJs 6.0.0
中,由于多种原因,这不起作用(仅Observable
方法是create
, interval
似乎是静态的,没有方法链接,...)。
How to do this in latest RxJs?如何在最新的 RxJs 中做到这一点?
I did not run it:我没有运行它:
interval(5000).pipe(
switchMap(() => this.apiService.getData())
).subscribe(data => /* ... */)
Interval
is now a function that returns an Observable and transformations are chained inside pipe
function. Interval
现在是一个返回 Observable 的函数,并且转换在pipe
函数内被链接起来。
Referencing LeeCampbell's RxCookbook about reactive programming.参考LeeCampbell关于反应式编程的 RxCookbook 。 Using interval is actually not practical.使用间隔实际上是不切实际的。 Because if you don't get a response from this.apiService.getData()
in the interval value another value will be emitted by the interval and a new request is performed.因为如果您没有在间隔值中从this.apiService.getData()
得到响应,则间隔将发出另一个值并执行新请求。
What you need to do is use a timer that emits a single value, use a switchMap to perform your request, and a repeat to poll again after success.您需要做的是使用发出单个值的计时器,使用 switchMap 执行您的请求,并在成功后重复轮询。 Also, you can use a retry before the repeat if you want to retry after errors.此外,如果您想在错误后重试,您可以在重复之前使用重试。
This is the implementation in C# using Rx.Net ( Ref ) :这是使用 Rx.Net ( Ref ) 在 C# 中的实现:
public static IObservable<T> Poll<T>(this IObservable<T> request, TimeSpan period, IScheduler scheduler)
{
return Observable.Timer(period, scheduler)
.SelectMany(_ => request)
.Retry() //Loop on errors
.Repeat(); //Loop on success
}
Which can be translated to RxJS 6 as following:可以翻译成 RxJS 6 如下:
timer(5000).pipe(
switchMap(tick => this.apiService.getData()),
retry(3), // retry 3 times before bubbling an error
repeat()
);
Further enhancements can be found in the LeeCampbell's RxCookbook .更多增强功能可以在LeeCampbell 的 RxCookbook 中找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.