Xamarin MessagingCenter: sending once, receiving multiples

426 Views Asked by At

I'm experiencing an annoying issue with xamarin messaging center. I added some break points and noticed that only one message is sent but the subscriber receives it twice.

My sender code(Page2):

async void CompartilhaMapa(System.Object sender, System.EventArgs e)
{ 

    ...        

   MessagingCenter.Send<Page2, ParamType>(this, "PopUpData", new ParamType() { Tipo = 2, Valor = Coords });
   Console.WriteLine("msg sent"); //displayed only once and line above has a break line assuring this
   await Navigation.PopPopupAsync();
}

Page1(Subscriber):

protected override void OnAppearing()
{
   base.OnAppearing();
   MessagingCenter.Subscribe<Page2, ParamType>(this, "PopUpData", async (sender, arg) =>
   {
      Task.WaitAll(tasks.ToArray());
      switch (arg.Tipo)
      {
          case 2:
             Console.WriteLine(" *********** msg received"); //this is outputted twice
             tasks.Add(Task.Run(() => ShareMap(arg))); //this is called twice
             break;
             case 3: tasks.Add(Task.Run(() => ShareEvent(arg))); break;
             case 6: tasks.Add(Task.Run(() => ShareImage(arg))); break;
      }
    });
}

protected override void OnDisappearing()
{
   base.OnDisappearing();
   MessagingCenter.Unsubscribe<Page2, ParamType>(this, "PopUpData");
}

What I'm doing wrong here?

1

There are 1 best solutions below

0
Saamer On

There are two possible reasons for this:

Reason 1 - The message is being sent more than once. Since you are insisting that it is sending only once, so I will ignore this. I still suggest that you should place a break point in your CompartilhaMapa function (sender code), to make sure that the function is in fact only called once.

Reason 2 - You have subscribed to the event more than once. To fix this,

  1. Place the subscribe event inside the constructor of page1 instead of inside the OnAppearing.
public Page1()
{
    ...
    MessagingCenter.Subscribe<Page2, ParamType>(this, "PopUpData", async (sender, arg) => ...

}
  1. Place the unsubscribe event inside the destructor of Page1 instead of inside the OnDisappearing. (You can even place this inside the OnBackButtonPressed override function instead of Page1)
~Page1()
{
    ...
    MessagingCenter.Unsubscribe<Page2, ParamType>(this, "PopUpData")
}

I have assumed Page1 is the name of the page, just replace it with the actual name.


Workaround - You have subscribed to the event more than once. To fix this,

  1. Place the unsubscribe event before any use of the subscribe event
public void SampleFunction()
{
    ...
    MessagingCenter.Unsubscribe<Page2, ParamType>(this, "PopUpData")
    MessagingCenter.Subscribe<Page2, ParamType>(this, "PopUpData", async (sender, arg) => ...

}