Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 91519

Multiple alerts with messagingcenter subscription

$
0
0

Hello,
I've a simple questione that I was unable to solve until now.
I've a viewmodel that try to load a list and a view that use it as bindingcontext.
I want that when the viewmodel fails to load the list simply display an alert and return to the previous page.

To do it I'm doing the following:

1-I subscribe my view to the message so it can show a popup when it receives a certain message:

protected override void OnAppearing()
{
if (!Helpers.IsRegistered)
{
MessagingCenter.Subscribe<ViewModelBase, string[]>(this, Helpers.POPUP_PROBLEM_OPEN_NEWS, (sender, values) =>
{
Helpers.IsRegistered = true;
Device.BeginInvokeOnMainThread(() =>
{
DisplayAlert(values[0], values[1], values[2]);
if (Navigation.NavigationStack.Count > 0)
Navigation.PopAsync();
});
});
}

        base.OnAppearing();

    }

2-when I have a problem in my viewmodel loading the list I send a message in this way (I putted all in an external helper class)

MessagingCenter.Send<ViewModelBase, string[]>(pSender, messageID, values);

I don't know why but the problem seems to be that my view is registered multiple times to the message: in fact it shows me the alert 2 times on the first execution, and then it increase exponentially evety time I reopen it.

I tried to use an external variable that tells me when I already have registered the view to this message and also to unregister them on OnDisappearing event, in this way:

protected override void OnDisappearing()
{
base.OnDisappearing();

        MessagingCenter.Unsubscribe<ViewModelBase>(this, Helpers.POPUP_PROBLEM_OPEN_NEWS);
        ((NewsViewModel)this.BindingContext).Registered = false;
    }

but it doesn't solve my problem.
Can somebody help me to understand what's wrong?

Thank you


Viewing all articles
Browse latest Browse all 91519

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>