Alan2
Alan2

Reputation: 24572

How can I make a method that runs in a MessagingCenter.Subscribe into an async method?

I have this code but it's failing as it expects my method to be async:

MessagingCenter.Subscribe<CardsViewModel, ParamViewModel>(this, "CardBtn", (s, cmdParams) =>
{
    if (Counts.phaseTableSelectedCardCount != 0)
    {
        var canContinue = await DisplayAlert("Selector", "Changing this will remove all previously selected cards from the deck", "OK", "Cancel");
        if (canContinue == false)
            return;
    }
    var settingId = vm.SetButtons(cmdParams);
    detailsLayout.Children.Clear();
    IsBusy = true;
    Change.cardSelection = true;
    await Task.Run(() => UpdateSettingsAndGetData(settingId));
    AddDetailSection();
    IsBusy = false;
});

Is there a way that I can add async to this and if so where would I need to add it?

Upvotes: 0

Views: 241

Answers (1)

Gerald Versluis
Gerald Versluis

Reputation: 34013

Sure, just add the async keyword before your parameters.

MessagingCenter.Subscribe<CardsViewModel, ParamViewModel>(this, "CardBtn", async (s, cmdParams) => ...

Notice how I added the async keyword after "CardBtn",. Remember that a lambda is just an inline method. You're simply declaring a method signature there, just without a few things.

I see that you're setting the IsBusy boolean, I take it that updates the UI. Beware that you might need Device.BeginInvokeOnMainThread to get to the UI thread since messaging happens on a background thread.

Upvotes: 3

Related Questions