Unable to implement Messaging Center , While implementing below process is happening

HI i need help in xamarin forms, i want to return value from Page 2 to Page 1. I'm using MessagingCenter but If i open Page2 and send a message to Page 1,it hits only once. Then if i close Page2 and open it again and send message, it hit twice.Like wise it is increases whenever i open and close Page2

Answers

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    where do you add subscribe and unsubscribe?

  • challashivachallashiva Member ✭✭

    Hi @AlessandroCaliaro Thank you for reply,
    I'm added Subscribe and Unsubscribe In Page 1, as shown in below code.

    protected override void OnAppearing()
    {
    base.OnAppearing();
    MessagingCenter.Unsubscribe<Page1, string>(this, "Hi");
    MessagingCenter.Subscribe<Page1, string>(this, "Hi", (sender, e) =>
    {
    currentLocation.Text = " Items near " + e;

            });
        }
    

    This is the send code from page 2 on Button click event

    saveButton.Clicked += async (sender, e) =>
    {
    MessagingCenter.Send(this, "Hi","Address");
    await Navigation.PopAsync();
    };

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭
    Usually is a good idea to Subscribe in OnAppearing and unsubscribe in InDisappearing. Try this
  • JohnHardmanJohnHardman GBUniversity mod

    @challashiva - Rather than use OnAppearing() for this, I'd look at using the Pushed and Popped events in NavigationPage, doing the subscription when Page1 is Pushed and unsubscribing when Page1 is Popped.

  • challashivachallashiva Member ✭✭

    Hi @AlessandroCaliaro i tried to put unsubscribe in OnDisappearing method in Page1, but Message in not coming from Page2,In Page1 Subscribe function is not hitting when return back from Page2

  • challashivachallashiva Member ✭✭

    Hi @JohnHardman Thank you for reply,
    I will try those method.

Sign In or Register to comment.