Hi everyone,
I'm having a bit of an issue with so called "zombie" pages and messaging center subscribers.
Let's say my application is structured as follows: LoginPage -> MenuPage -> PageA -> PageB
In each of the PageA and PageB I subscribe to the messaging center messages in the OnAppearing method and then unsubscribe in the OnDisappearing method, since I only want to listen to the messages when the page is active (displayed). If I navigate directly from page to page everything is working correctly.
However I am checking the user session when OnAppearing of each of the PageA and PageB is called, and if the user session has expired, I return the user to the first page (LoginPage). In order to achieve this, I created a helper method in my App class, which replaced the current MainPage (as was suggested on other threads on this page):
public void ClearNavigation()
{
MainPage = new NavigationPage(new Login());
}
So for example if I call the ClearNavigation in my PageB page, the OnDisappearing method will be called and with it the unsubscribe call to the message. After that, the LoginPage will be shown. I'm checking the NavigationStack size, and it is 1, so everything is looking ok.
However:
If I trigger a message, that each of the pages is subscribing/unsubscribing to, something really weird will happen. The message will get to the PageB (it will actually trigger a breakpoint in the PageB), which is not in the current NavigationStack, and was unsubscribed in the OnDisappearing method (and OnAppearing was not called after that).
So 2 things are really strange here:
1. The page still lives in memory, after the MainPage was replaced. In fact all pages still live in the memory, since if I check the NavigationStack of the page which receives the message, it's different than the one I'm currently on (the one with only 1 page) I'm guessing this is not the correct way to reset your application in that case...)? I tried using the .PopToRootAsync() method, but that usually results into exception and Application crash.
2. The message is hitting it's subscriber, even if it was unsubscribed (and not subscribed again). So it looks like the OnDisappearing does not finish executing in the event that the MainPage is replaced, or something?)
Does anyone has any similar experience or would be able to give me a insight into what is causing this strange and unwanted behavior? Is this normal behaviour or maybe an Xamarin.Forms bug? I am using the version 3.6, but the problem was the same in the 3.5, I didn't test any other versions.
BR,
Denis