无功扩展计时器/间隔重置 [英] Reactive extension Timer/Interval reset

查看:58
本文介绍了无功扩展计时器/间隔重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,除非在此期间进行任何更新,否则我需要每10秒发送一次状态消息.意思是,每次更新时,计时器都会重置.

I have a project where I need to send a status message every 10 seconds unless there's been an update in the meantime. Meaning, every time there would be an update, the timer would reset.

var res = Observable
  .Interval(TimeSpan.FromSeconds(10))
  .Where(_ => condition);

res.Subscribe(_ => Console.WriteLine("Status sent."));

现在,我知道仅在计时器结束时才应用哪里",所以它没有帮助.但是,我想知道是否有一种方法可以重置时间间隔;或重复使用Timer().

Now I know that the "Where" will only be applied when the timer ends, so it doesn't help. But, I'm wondering if there's a way to reset the Interval; or to use a Timer() with a repeat.

推荐答案

使用标准Rx运算符很容易实现.

This is pretty easy to implement using standard Rx operators.

您的问题中尚不清楚的是什么是更新".我将假设您具有某种可观察到的值,可在每次更新时触发,或者您可以创建一个主题,在有更新时将其称为 .OnNext(...).没有可观察到的更新,很难知道何时重置计时器.

What isn't clear from your question is exactly what an "update" is. I'm going to assume that you have some sort of observable that fires for every update or that you can create a subject that you'll call .OnNext(...) when there is an update. Without observable updates it is hard to know when to reset the timer.

所以这是代码:

var update = new Subject<bool>();

var res =
    update
        .Select(x => Observable.Interval(TimeSpan.FromSeconds(10.0)))
        .Switch();

res
    .Subscribe(_ => Console.WriteLine("Status sent."));

update.OnNext(true);

res 查询现在等待,直到从 update 获取值,然后选择一个新的 Observable.Interval .这意味着在 Select 之后,该类型为 IObservable< IObservable< long>> ,因此需要 .Switch()进行转换放入 IObservable< long> 中. .Switch()通过仅传出最新观察到的可观察值并处置任何先前可观察到的值来做到这一点.换句话说,对于每个 update ,都会启动一个新计时器,并取消先前的计时器.这意味着,如果您的更新发生的频率超过10秒,则计时器将永远不会触发.

The res query now waits until it gets a value from update and then it selects a new Observable.Interval. This means that after the Select the type is an IObservable<IObservable<long>>, so the .Switch() is required to turn it in to a IObservable<long>. .Switch() does this by only passing out values from the latest observed observable and disposing of any previous observables. In other words, for each update a new timer is started and the previous timer is cancelled. This means that if you have updates occurring more frequently than 10 seconds then the timer will never fire.

现在,如果可观察的 res 本身就是一个更新,那么您可以执行以下操作:

Now, if the res observable is an update in its own right, then you can do this:

res
    .Subscribe(_ =>
    {
        update.OnNext(true);
        Console.WriteLine("Status sent.");
    });

那很好-它仍然可以工作,但是对于每个计时器,触发 res 都会创建一个新计时器.这意味着依靠您的 update 可观察/主题的任何事物仍然可以正常运行.

That's fine - it still works, but for each timer firing res will create a new timer. It will mean that anything relying on your update observable/subject will still function correctly.

这篇关于无功扩展计时器/间隔重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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