如何将以下类转换为IObservable?

时间:2016-05-04 02:36:54

标签: c# system.reactive

我有以下课程

namespace TickRateEntity
{
    public struct TickRateData
    {
        public double tickrate;
    }

    public class TickRate
    {
        private TickRateData tickRateData;
        //etc
    }
}

如何更改这些类以便每隔n分钟说一次,TickRate或TickRateData数据会发布双tickrate

2 个答案:

答案 0 :(得分:1)

假设您有一个带有签名TickRate GetTickRate()的方法,那么这可行:

int n = 5;
IObservable<double> query =
    from x in Observable.Interval(TimeSpan.FromMinutes(n))
    let tickRate = GetTickRate()
    select tickRate.tickRateData.tickrate;

IDisposable subscription = query.Subscribe(x => /* do something with `x` */);

否则,如果以其他方式生成TickRate,我们需要知道如何回答这个问题。

答案 1 :(得分:1)

假设您的tickRateData以某种方式填充,那么您可以执行以下操作:

public class TickRate : IDisposable
{
    private TickRateData tickRateData;
    private readonly IDisposable _subscription;

    public IObservable<double> Stream { get; }

    public TickRate(double intervalInMinutes)
    {
        var stream = Observable.Interval(TimeSpan.FromMinutes(intervalInMinutes))
                               .Select(_ => tickRateData.tickrate)
                               .Publish();

        _subscription = stream.Connect();

        Stream = stream;
    }

    public void Dispose()
    {
        _subscription?.Dispose();
    }
}