2

I have the following classes

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

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

How do change these classes so that say every n minutes, either TickRate or TickRateData data publishes the double tickrate?

Ivan
  • 7,448
  • 14
  • 69
  • 134

2 Answers2

1

Assuming you have a method with the signature TickRate GetTickRate() then this works:

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` */);

Otherwise if TickRate is being generated some other way the we need to know how to answer this question.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • But I am confused, that pulls the data not pushes it? I don't quite understand the relationship between Observables and Observers? Where is the Observer in your example? Where is Publish, Where is Subscribe? What if there are multiple subscribers? – Ivan May 04 '16 at 03:24
  • What function does that code live in? How does one tie all the loose ends? Where is OnNext? – Ivan May 04 '16 at 03:31
  • @Ivan - The query pushes the values, but the call to `GetTickRate()` is only there because you haven't said how `TickRate` is populated. If you can provide the right mechanism I can answer the rest of your questions. – Enigmativity May 04 '16 at 04:32
  • @Ivan - You should avoid using a `Subject`. – Enigmativity May 04 '16 at 04:32
  • Took your advice and used the chosen answer below. Works great. – Ivan May 10 '16 at 15:54
1

Assuming your tickRateData is somehow populated, then you could do something like this:

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();
    }
}
ionoy
  • 975
  • 6
  • 19