Forum Xamarin.Forms

MessagingCenter: How to prevent the same message from being run multiple times?

AdrianKnightAdrianKnight USMember ✭✭✭✭

I don't have time to test this at the moment, but It keeps bugging me not to know the answer.

Suppose I subscribe to a message on an instance of CustomContentPage (subscriber) to CustomContentPage2 (sender). Suppose I push two instances of CustomContentPage on the navigation stack and then an instance of CustomContentPage2. When a message is sent from CustomContentPage2, will it be run on both CustomContentPage instances or the one that comes before CustomContentPage2? To prevent the message from being processed by both pages, what should I do?


  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    It will be run where you have subscribed the message.
    If you want run the message only on the last CustomContentPage, you can Dismiss the Message on "OnDisappearing"

  • MommMomm USMember ✭✭✭
    edited April 2016

    You should subscribe on the OnAppearing method and unsubscribe on the OnDisappearing. By doing it, you should have no problems.

  • Matthew.4307Matthew.4307 USMember ✭✭✭

    The catch is OnAppearing and OnDisappearing are now unreliable on Android and Windows (Forms 2.2) so you can't guarantee they fire.

  • AdrianKnightAdrianKnight USMember ✭✭✭✭

    Thanks. Do I need to unsubscribe if the page is removed from the navigation stack as opposed to being "hidden"?

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    Yes Adam. If you add your unsubscribe in OnDisappearing, should be enough

Sign In or Register to comment.