I am subscribing popup pages in Content pages with different key names(Eg X,Y...Z). I am using these popup pages to show error ,user messages and etc.
Problem is , i can see that the action of subscriber is called more than a time whenever i send the messages .I assume it is because that the message center is subscribed same messages multiple times even i unsubscribe first.
If i open "MyPage" and send a message ,it hit only once. Then if i close "MyPage" and open it again and send message, it hit twice.Like wise it is increases whenever i open and close MyPage.
I guess it is because of the multiple subscriptions of same messages. How can i prevent this behavior for message center?
Code
Public MyPage:ContentPage { public MyPage() { SubcribeAlerts(); } } public SubcribeAlerts() { //unsubscribe first MessagingCenter.Unsubscribe<AltertModel>(this, "X"); MessagingCenter.Unsubscribe<AlertDialogModel>(this, "Y"); //subscribe MessagingCenter.Subscribe<AltertModel>(this, "X", async (args) => { if (!string.IsNullOrEmpty(args.MessageText)) { await PopupNavigation.PushAsync(new DisplayAltertPage(args.MessageText, (result) => { args.ViewModelCallBack(result); })); } }); MessagingCenter.Subscribe<AlertDialogModel>(this, "Y", async (args) => { if (!string.IsNullOrEmpty(args.MessageText)) { await PopupNavigation.PushAsync(new DisplayAlertDialogPage(args.MessageText, (result) => { args.CallBack(result); })); } }); }
OnAppearing and OnDisappearing are good places to Subscribe and Unsubscribe
Answers
If you subscribe in the constructor consider unsubscribing in the destructor.
Unsubscribing during creation wouldn't get you anywhere because that instance of the class wasn't subscribed.
If you unsubscribe during the destruction of the class then it can reference itself.
OnAppearing and OnDisappearing are good places to Subscribe and Unsubscribe
@ClintStLaurent Thank you .I really forget the destructor. Any way i prefer to do it in onApprearing and onDesappearing as @AlessandroCaliaro mentioned .