How to unsubscribe from messaging center when using the ON SCREEN back button on android?

Viewed 79

I am trying to unsubscribe from the messaging center when the user uses the back button (top left) on a certain page. I am already doing it for the hardware back button

protected override bool OnBackButtonPressed()
        {

            MessagingCenter.Unsubscribe<App, string>(this, "Trolley");
            return base.OnBackButtonPressed();
        }

But it does not work for the back button showing on screen. I am aware of the existence of "OnDisappearing" but it does not work in my case because I actually need it to work when entering a new page.

I am on Page 1 and subscribe to "Trolley" then I load page 2, send a message "Trolley" and finally close page 2. OnDisappearing triggers when I load page 2 so I wouldn't be able to receive the message if I where to unsubscribe in OnDisappearing.

1 Answers

First, you need to understand about Xamarin Life Cycle. And by overriding OnBackButtonPressed() will only work when you tap physical back button (near Home button) on Android devices only.

For your case, I think you need to use PageAppearing to subscribe and use PageDisappearing when you want to unsubscribe.

There is no OnPushed or OnPopped for non modal page. If you wish a method like that you need to customize your logic.

EDIT

i found an example of a way to do this https://gist.github.com/housecode/33c11faecff2d7be39f3b7503a686527

Here the code from the gist

Extending Xamarin.Forms NavigationPage to add OnPushed and OnPopped event. Just implement IPageEvent to any Page you want to add those methods and change your NavigationPage with ExtNavPage.

public class ExtNavPage : NavigationPage
{
    public ExtNavPage(Page page) : base(page)
    {
        this.AddNavigationEvent();
    }

    private void AddNavigationEvent()
    {
        Popped += (s, e) => NavEventHandle(e, true);
        PoppedToRoot += (s, e) => NavEventHandle(e, true);
        Pushed += (s, e) => NavEventHandle(e);
    }

    private void NavEventHandle(NavigationEventArgs e, bool isPop = false)
    {
        if (e.Page is IPageEvent pe) {
            if (isPop)
                pe.OnPopped();
            else
                pe.OnPushed();
        }
    }
}

public interface IPageEvent
{
    void OnPopped();
    void OnPushed();
}
Related