Search code examples
c#reactiveuireactivexavaloniauiavalonia

how to detect two property in reactiveui


I am using reactiveui.

I want to run a some task based on the state of 2 properties.

How can I make the task run when sw1 is true and sw2 is false?

I tried as below but it doesn't work.

    private bool Ch1SW { get; set; }
    private bool Ch2SW { get; set; }
    
    this.WhenAnyValue(x => x.Ch1SW , x => x.Ch2SW , (sw1, sw2) => (sw1, sw2))
        .Where(sw => sw.sw1 == true && sw.sw2 == false)
        .ObserveOn(RxApp.MainThreadScheduler)
        .Subscribe(async x => { //some work });

Solution

  • The properties have to be public and you need to have the property changed mechanism implemented. If you are using reactiveui the easiest way is to add the [Reactive] attribute over the property declaration (from the ReactiveUI.Fody package). Then the WhenAnyValue will return the IObservable you can directly subscribe to and execute your function.

    [Reactive]
    public bool Ch1SW { get; set; }
    [Reactive]
    public bool Ch2SW { get; set; }
    
    public MyViewModel()
    {
        this.WhenAnyValue(x => x.Ch1SW, x => x.Ch2SW).Subscribe(MyAsyncFunc);
    }
    
    private async void MyAsyncFunc((bool, bool) chsw)
    {
        if (chsw.Item1 && !chsw.Item2)
        {
            await System.Threading.Tasks.Task.Delay(500);
            Debug.WriteLine("Done!");
        }
    }
    
    

    EDIT: The [Reactive] still requires the class to inherit from ReactiveObject