2

I want to make communication with serial port - get some data. I want to get this data in loop as fast as it's possible. So, i have function GetData() with callback, which draws data on the WPF form. How can I call this GetData function in loop right after all it's callbacks?

Like cycle GetData->Draw->GetData->Draw and so on?

Upd: Mb something like this?

var ob = Observable.Create<Data>(
  observer => {
    while(true) {
      observer.OnNext(GetDataFromSerialPort());
    }
});
Virviil
  • 622
  • 5
  • 14

1 Answers1

4

I would create a service that exposed the serial Port data via an observable sequence. I would then inject that into my MVVM stack.

The Service would like similar to what you have, but with disposal functionality

public class MySerialPortService : IsCancellationRequested
{
    public IObservable<Data> GetData()
    {
        return Observable.Create<Data>(async (o, cts) =>
          observer => {
            while (!cts.IsCancellationRequested) {
              observer.OnNext(GetDataFromSerialPort());
            }
        });
    }
}

public class MyViewModel : IDisposable
{
    private readonly IMySerialPortService _mySerialPortService;
    private readonly ISchedulerProvider _schedulerProvider;
    private readonly SingleAssignmentDisposable _subscription = new SingleAssignmentDisposable();

    public MyViewModel(IMySerialPortService mySerialPortService, ISchedulerProvider schedulerProvider)
    {
        _mySerialPortService = mySerialPortService;
        _schedulerProvider = schedulerProvider;
    }

    public void Start()
    {
        _subscription.Disposable = _mySerialPortService.GetData()
            .SubscribeOn(_schedulerProvider.Background) //or _schedulerProvider.ThreadPool, or CreateEventLoopScheduler or what ever you do internally.
            .ObserveOn(_schedulerProvider.Foreground)   //or _schedulerProvider.Dispatcher etc...
            .Subscribe(
                val=> Update(val),
                ex=> ...
            )
    }

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

The following post may be helpful - https://github.com/LeeCampbell/RxCookbook/tree/master/IO/Disk. It shows you step by step how to create and Observable Sequence that reads from Disk. You can swap the Disk IO for Serial Port IO.

Lee Campbell
  • 10,631
  • 1
  • 34
  • 29