Dominic Jonas
Dominic Jonas

Reputation: 5005

RX: How to bind an IObservable<object> to a property (ReactiveUI)

I have class MyClient with an IObservable<IStatus> (Client.StatusStream()). Now I would like to combine ReactiveX and ReactiveUI. But the documentation is not providing any example how to use them together.

I have tried some extension methods so far (f.e. .ToProperty), but they are not working.

public partial class MainWindow : ReactiveWindow<AppViewModel>
{
    public MainWindow()
    {
        InitializeComponent();
        ViewModel = App.Container.GetInstance<AppViewModel>();
        this.WhenActivated(r =>
            {
                this.OneWayBind(ViewModel, viewModel => viewModel.Status.AoiStatus, view => view.StatusTxtbl.Text).DisposeWith(r);
                this.OneWayBind(ViewModel, viewModel => viewModel.Status.OperationMode, view => view.OpModeTxtbl.Text).DisposeWith(r);
                this.OneWayBind(ViewModel, viewModel => viewModel.Status.TestPlan, view => view.TestplanTxtbl.Text).DisposeWith(r);
            });
    }

    private async void ButtonGetStatus_OnClick(object sender, RoutedEventArgs e)
    {
        // the manual mode to get the actual status information
        var status = await ViewModel.Client.GetStatusAsync();
        ViewModel.Status = status;
    }
}

public class AppViewModel : ReactiveObject
{
    private IStatus _Status;
    public IStatus Status
    {
        get => _Status;
        set => this.RaiseAndSetIfChanged(ref _Status, value);
    }

    public MyClient Client { get; }

    public AppViewModel(MyClient client)
    {
        Client = client;
        // automatically pushes every new status information
        Client.StatusStream(); // <- How to get the data out there?
    }
}

Info

To notify the gui about new updates, to have to use ObserveOnDispatcher, see https://stackoverflow.com/a/55811495/6229375

Upvotes: 1

Views: 1244

Answers (1)

mm8
mm8

Reputation: 169160

Define Status as an output property:

public class AppViewModel : ReactiveObject
{
    private readonly ObservableAsPropertyHelper<IStatus> _status;
    public string Status => _status.Value;

    public MyClient Client { get; }

    public AppViewModel(MyClient client)
    {
        Client = client;
        Client.StatusStream().ToProperty(this, x => x.Status, out _status);
    }
}

Upvotes: 4

Related Questions