Question

I am fairly new to reactive UI. I am using it in my app extensively for async programming etc.

I have a question. I have a method in my ViewModel which is async and which "awaits" for a task to complete. On completion of this task, I would like to notify my view (a UserControl) so it can dynamically add some more content/UserControls, to say, a DockPanel.

What is the best way of doing this using ReactiveUI or RX? I could use C# event mechanism , etc. but I want to continue down the RX path. I set a boolena property in my VM when the async method has "completed" (i.e. returned from await).

I then want to observe for this boolean property (defined in my VM) in my "View"..so I can attach a handler in my "View" which will dynamically create some UserControls, e.g.

this.viewModel.ObservableForProperty(x => x.DataLoaded)
              .Subscribe(async _ => await this.MyViewHandler()); 
// this does not compile as the delegate is not IObserver type in my view it says

Any guidance will be much appreciated, many thanks.

Was it helpful?

Solution

You've mostly got the right idea, just need some work on the syntax:

this.WhenAnyValue(x => x.ViewModel.DataLoaded)
    .Where(x => x == true)
    .Subscribe(_ => MyViewHandler());

OTHER TIPS

The problem with your example code is that as the compiler says, you are not passing a valid IObserver implementation to the Subscribe method. You are actually passing an Func<boolean, Task> where it is expecting an Action<boolean> implementing the IObserver.OnNext.

I haven't tried ReactiveUI, but I think you can accomplish but you intend with either Task Continuation or with the IObserver.OnCompleted. A couple ideas are:

  • Using Task Continuation you'd launch another task once the one you mentioned has finished. You can do this by appending a .ContinueWith call to your task. Keep in mind that code from the continuation task modifying the UI must be dispatched to the UI thread from the continuation task (either using the Dispatcher or by passing the proper TaskScheduler to ContinueWith).

  • With RX, you could create a sequence for your task with the proper Observable.Create factory method or simply using the Task.ToObservable extension methods, then subscribe to it and do whatever you want on the OnCompleted handler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top