Switch -> EventToCommand: Detect if Toggled from user interaction or from webservices/websocket sync

MatteoPiccioniMatteoPiccioni USMember ✭✭

Hello,
first of all, sorry for my english

I have a page with a number of Switch..each switch turn on/off a remote light using webservices.
To make this I used behaviors and Command in ViewModel linked to Toggled event (we call it SetOnOffSwitchCommand)

At page appearing I call a command to load the real state of each switch (we call it OnAppearingCommand),
In this command I call a w.s. and I set on or off each Switch using a IsToggled binded property
Each time I set on or off a Switch, my 'SetOnOffSwitchCommand' is called, and this is not good.
To fix this problem I add in 'SetOnOffSwitchCommand' a way to exit the command without calling the ws:
if (isBusy) then return;
In fact in my OnAppearingCommand I have a 'IsBusy' boolean used to show an ActivityIndicator.

The problem is that I use websocket too, to update the switch status while the user has the page opened.
If a websocket specific message is received, I call a third command in my viewmodel (SetOnOffFromWebServicesCommand)
The problem is that, also using the 'IsBusy' trick, when I change the state of a Switch, the SetOnOffSwitchCommand is called, and the IsBusy flag is set to false form the SetOnOffFromWebServicesCommand before the SetOnOffSwitchCommand is called.

Exist a sure way to fix my problem?
Thanks!

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    If you don't want to trigger the switch's toggled command, you could use public Command(Action execute, Func<bool> canExecute);. Define Another property in your view model called canSwitchExecute and your switch's trigger command may be like:

    ToggledCommand = new Command(() =>
    {
        // This command can only be triggered when canSwitchExecute and IsBusy are both true.
    }, () =>
    {
        return canSwitchExecute && IsBusy;
    });
    

    Then set the value to false when you are loading the data from your service:

    canSwitchExecute = false;
    
    // Loading...
    
    await Task.Delay(100);
    canSwitchExecute = true;
    
  • MatteoPiccioniMatteoPiccioni USMember ✭✭
    edited April 30

    Thanks, sorry for late reply
    I will try asap...for now I move the command from the switch to the row click
    ps. chrome doesnt let me answer or write to forum

  • NMackayNMackay GBInsider, University mod

    @MatteoPiccioni said:
    Thanks, sorry for late reply
    I will try asap...for now I move the command from the switch to the row click
    ps. chrome doesnt let me answer or write to forum

    Forum works fine with chrome, maybe you have a plugin running that's restricting the page.

Sign In or Register to comment.