动态定时器可观察 [英] Dynamic timer observable

查看:42
本文介绍了动态定时器可观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临一个与如何创建动态计时器"可观察对象相关的问题.

我的意思是,我需要执行一个函数,并根据它返回的值(表示秒数的整数),在这些秒过去后我需要调用相同的函数.所以,我想我需要根据另一个新值秒重新安排可观察对象.

我试图在那里找到一些东西,但我一直无法弄清楚我需要做什么.

有什么想法吗?

解决方案

使用 Observable.Generate.试试这个例子:

void Main(){可观察的.产生(0,//初始状态x =>×<10,//条件x =>x + 1,//迭代x =>x,//结果选择器x =>TimeSpan.FromSeconds(GetSeconds()))//timeSelector.时间戳().Subscribe(x => Console.WriteLine($"{x.Value} {x.Timestamp}"));}私人双_秒 = 2.0;公共双 GetSeconds(){如果 (++_seconds > 5.0){_秒 = 2.0;}返回_秒;}

它产生以下输出:

<前>0 2017/09/27 12:47:24 +00:001 2017/09/27 12:47:28 +00:002 2017/09/27 12:47:33 +00:003 2017/09/27 12:47:35 +00:004 2017/09/27 12:47:38 +00:005 2017/09/27 12:47:42 +00:006 2017/09/27 12:47:47 +00:007 2017/09/27 12:47:49 +00:008 2017/09/27 12:47:52 +00:009 2017/09/27 12:47:56 +00:00

第一个结果出现在 3.0 秒后(因为初始 ++seconds)和 4.0 秒后的下一个值,如时间戳的差异.

由于 x => 它在 10 个值后停止;×<10,//条件.

I'm facing with an issue related with how to create a dynamic "timer" observable.

Slightly I mean, I need to perform a function and according the value it returns (integer representing the number of seconds) I need to call the same function after these seconds have elapsed. So, I guess I need to re-schedule the observable according this another new value seconds.

I've tried to find something overthere but I',ve not been able to figure out what do I need to do.

Any ideas?

解决方案

Use Observable.Generate. Try this example:

void Main()
{
    Observable
        .Generate(
            0, // initialState
            x => x < 10, //condition
            x => x + 1, //iterate
            x => x, //resultSelector
            x => TimeSpan.FromSeconds(GetSeconds())) //timeSelector
        .Timestamp()
        .Subscribe(x => Console.WriteLine($"{x.Value} {x.Timestamp}"));
}

private double _seconds = 2.0;

public double GetSeconds()
{
    if (++_seconds > 5.0)
    {
        _seconds = 2.0;
    }
    return _seconds;
}

It produces the following output:

0 2017/09/27 12:47:24 +00:00
1 2017/09/27 12:47:28 +00:00
2 2017/09/27 12:47:33 +00:00
3 2017/09/27 12:47:35 +00:00
4 2017/09/27 12:47:38 +00:00
5 2017/09/27 12:47:42 +00:00
6 2017/09/27 12:47:47 +00:00
7 2017/09/27 12:47:49 +00:00
8 2017/09/27 12:47:52 +00:00
9 2017/09/27 12:47:56 +00:00

The first result appears after 3.0 seconds (because of the initial ++seconds) and the next value after 4.0 seconds as seen by the difference in the timestamp.

It stops after 10 values due to the x => x < 10, //condition.

这篇关于动态定时器可观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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