title: MessagingCenter Unsubscribe not working in xamarin forms when using between viewmodels
body: <p>I'm working on Xamarin Forms. Unsubscribe is not working in <code>MessagingCenter</code> when using between view models. </p>
  
  <p>I'm trying to unsubscribing <code>messagingCenter</code> on <code>OnDisappear()</code> in <code>ContentPage</code>. The reason why I want to unsubscribing is because when I subscribing, it count as twice and the message also sent twice. It should not receive more than 1 time, same as subscribe too. Below my code.</p>
  
  <p><strong>BottomTabsViewModel where subscribing:</strong></p>
  
  <pre><code>   using RCBazaar.Base.ViewModels;
  using RCBazaar.Services.Interfaces;
  using RCBazaar.ViewModels.Base;
  using System;
  using System.Collections.Generic;
  using System.Runtime.CompilerServices;
  using System.Text;
  using System.Windows.Input;
  using Xamarin.Forms;
  
  namespace RCBazaar.ViewModels
  {
      public class BottomTabsViewModel : ViewModelBase
      {
          public ICommand HomeCommand =&gt; new Command(HomeTab_Clicked);
          public ICommand CategoriesCommand =&gt; new Command(CategoriesTab_Clicked);
          public ICommand CartCommand =&gt; new Command(CartTab_Clicked);
          public ICommand ChatCommand =&gt; new Command(ChatTab_Clicked);
          private string _badgeText;
          private bool _isActiveHome;
          public bool IsActiveHome
          {
              get
              {
                  return _isActiveHome;
              }
              set
              {
                  _isActiveHome = value;
                  RaisePropertyChanged(() =&gt; IsActiveHome);
              }
          }
  
          private bool _isActiveCategory;
          public bool IsActiveCategory
          {
              get
              {
                  return _isActiveCategory;
              }
              set
              {
                  _isActiveCategory = value;
                  RaisePropertyChanged(() =&gt; IsActiveCategory);
              }
          }
  
          private bool _isActiveCart;
          public bool IsActiveCart
          {
              get
              {
                  return _isActiveCart;
              }
              set
              {
                  _isActiveCart = value;
                  RaisePropertyChanged(() =&gt; IsActiveCart);
              }
          }
  
          private bool _isActiveChat;
          public bool IsActiveChat
          {
              get
              {
                  return _isActiveChat;
              }
              set
              {
                  _isActiveChat = value;
                  RaisePropertyChanged(() =&gt; IsActiveChat);
              }
          }
  
          public string BadgeText
          {
              get
              {
                  return _badgeText;
              }
              set
              {
                  _badgeText = value;
                  RaisePropertyChanged(() =&gt; BadgeText);
              }
          }
  
  
  
          public static string IsSelected { get; set; }
  
  
  
          public BottomTabsViewModel()
          {
  
  
              BadgeCount();
  
  
              if (IsSelected == "Home")
              {
                  ActiveHome();
              }
              else if (IsSelected == "Category")
              {
                  ActiveCategory();
              }
              else if (IsSelected == "Cart")
              {
                  ActiveCart();
              }
              else if (IsSelected == "Chat")
              {
                  ActiveChat();
              }
              else
              {
                  ActiveHome();
              }
          }
  
          private void BadgeCount()
          {
  
              //Subscriber listen for the specific message. Here getting data for refresh the listView when add item to the database.
              MessagingCenter.Subscribe&lt;ProductDetailsViewModel, string&gt;(this, "ShoppingCartCount", (sender, arg) =&gt;
              {
                  try
                  {
                      if (arg != null)
                      {
                          BadgeText = arg;
                      }
                  }
                  catch (Exception ex)
                  {
                  }
              });
          }
  
  
          public void HomeTab_Clicked()
          {
              IsSelected = "Home";
              NavigationService.NavigateToAsync&lt;HomeProductsViewModel&gt;();
          }
  
          public void CategoriesTab_Clicked()
          {
              IsSelected = "Category";
              NavigationService.NavigateToAsync&lt;MainCategoriesListViewModel&gt;();
          }
  
          public void CartTab_Clicked()
          {
              IsSelected = "Cart";
              NavigationService.NavigateToAsync&lt;AccordianViewModel&gt;();
          }
  
          public void ChatTab_Clicked()
          {
              IsSelected = "Chat";
              NavigationService.NavigateToAsync&lt;RCBazaarInformationViewModel&gt;("Contact us");
          }
  
          public void ActiveHome()
          {
              IsActiveHome = true;
              IsActiveCategory = false;
              IsActiveCart = false;
              IsActiveChat = false;
          }
  
          public void ActiveCategory()
          {
              IsActiveHome = false;
              IsActiveCategory = true;
              IsActiveCart = false;
              IsActiveChat = false;
          }
  
          public void ActiveCart()
          {
              IsActiveHome = false;
              IsActiveCategory = false;
              IsActiveCart = true;
              IsActiveChat = false;
  
          }
          public void ActiveChat()
          {
              IsActiveHome = false;
              IsActiveCategory = false;
              IsActiveCart = false;
              IsActiveChat = true;
          }
  
  
      }
  }
  </code></pre>
  
  <p>** ProductDetailViewModel where sending message:**</p>
  
  <pre><code> using FFImageLoading.Forms;
  using Plugin.Share;
  using Plugin.Share.Abstractions;
  using RCBazaar.Base.ViewModels;
  using RCBazaar.Model.ShoppingCart;
  using RCBazaar.Services.Interfaces;
  using RCBazaar.Services.Products;
  using RCBazaar.ViewModels;
  using RCBazaar.Views;
  using Rg.Plugins.Popup.Services;
  using System;
  using System.Collections.Generic;
  using System.Collections.ObjectModel;
  using System.Diagnostics;
  using System.Text;
  using System.Threading.Tasks;
  using System.Windows.Input;
  using Xamarin.Forms;
  
  [assembly: Dependency(typeof(ProductDetailsViewModel))]
  namespace RCBazaar.ViewModels
  {
      public class ProductDetailsViewModel : ViewModelBase
      {
          private Product _productDetails;
          private string _productName;
          private long _productStock;
          private double _productPrice;
          private string _productDescription;
          private ObservableCollection&lt;string&gt; _productImage;
          private string _productSKU;
          private ObservableCollection&lt;CartItem&gt; _basketItems;
          private Color _badgeColor;
  
          private long _productId;
  
          private string _overviewColor;
          private string _reviewsColor;
          private bool _productDescriptionIsVisible;
          private long _productRating;
          private string _badgeText;
  
  
          public ProductDetailsViewModel()
          {
              try
              {
  
  
                  BasketItems = new ObservableCollection&lt;CartItem&gt;();
  
                  BadgeText = "0";
                  OverviewColor = "#231f20";//blue color
                  ReviewsColor = "#DCDCDC";//lightgray
                  ProductDescriptionIsVisible = true;
                  ReviewIsVisible = false;
                //  _navigation = navigation;
  
  
  
  
                  var images = new List&lt;string&gt;() { "CourselStaticImage3.jpeg", "CourselStaticImage2.jpeg", "CourselStaticImage1.jpeg", "CourselStaticImage4.jpeg" };
  
                  ProductImage = new ObservableCollection&lt;string&gt;(images);
  
  
  
                  OnRatingChanged();
  
                  MyCommand = new Command(() =&gt;
                  {
                      Debug.WriteLine("Position selected.");
                  });
  
                  int[] numbers = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
                  List&lt;WareHouse&gt; wareHouses = new List&lt;WareHouse&gt;()
                  {
                      new WareHouse {WarehouseId=1, WareHouseName= "Banglore outlet", Items= numbers },
                      new WareHouse {WarehouseId=2, WareHouseName= "Pune outlet", Items= numbers },
                      new WareHouse {WarehouseId=3, WareHouseName= "Mumbai outlet", Items= numbers }
                  };
  
                  ListHeight = wareHouses.Count * 30;
  
                  WareHouses = new ObservableCollection&lt;WareHouse&gt;(wareHouses);
  
                  Reviews = new ObservableCollection&lt;Review&gt; { new Review { ReviewTitle="title",ReviewText="text",rating=2,IsReviewHelpful=true},
                  new Review { ReviewTitle="title",ReviewText="text",rating=4,IsReviewHelpful=false},
                  new Review { ReviewTitle="title",ReviewText="text",rating=0,IsReviewHelpful=true},
                  new Review { ReviewTitle="title",ReviewText="text",rating=2,IsReviewHelpful=true},
                  new Review { ReviewTitle="title",ReviewText="text",rating=4,IsReviewHelpful=false},
                  new Review { ReviewTitle="title",ReviewText="text",rating=0,IsReviewHelpful=true},
                  new Review { ReviewTitle="title",ReviewText="text",rating=2,IsReviewHelpful=true},
                  new Review { ReviewTitle="title",ReviewText="text",rating=4,IsReviewHelpful=false},
                  new Review { ReviewTitle="title",ReviewText="text",rating=0,IsReviewHelpful=true},
                  };
  
              }
  
              catch (Exception ex)
              {
  
              }
          }
          public class Review
          {
              public string id { get; set; }
              public string ReviewTitle { get; set; }
              public string ReviewText { get; set; }
              public float rating { get; set; }
              public string CreatedDate { get; set; }
              public bool IsReviewHelpful { get; set; }
          }
  
          private ObservableCollection&lt;Review&gt; _reviews;
          public ObservableCollection&lt;Review&gt; Reviews
          {
              get
              {
                  return _reviews;
              }
              set
              {
                  _reviews = value;
                  RaisePropertyChanged(() =&gt; Reviews);
              }
          }
  
          public override async Task InitializeAsync(object navigationData)
          {
  
              _productDetails = (Product)navigationData;
              ProductName = _productDetails.Name;
              ProductStock = _productDetails.Qtyonhand;
              ProductPrice = _productDetails.pricelist;
              ProductDescription = _productDetails.FullDescription;
              ProductRating = _productDetails.RatingSum;
              //   ProductImage = _productDetails.PictureBinary;
              ProductId = _productDetails.ProductId;
              ProductSKU = _productDetails.upc;
              //// Update Basket/badgecount
              //var basket = await _basketService.GetBasketAsync(userInfo.UserId, authToken);
  
              //if (basket != null &amp;&amp; basket.Items != null &amp;&amp; basket.Items.Any())
              //{
              //    BadgeCount = 0;
              //    BasketItems.Clear();
  
              //    foreach (var basketItem in basket.Items)
              //    {
              //        BadgeCount += basketItem.Quantity;
              //        await AddBasketItemAsync(basketItem);
              //    }
              //}
          }
          //private async Task AddBasketItemAsync(BasketItem item)
          //{
          //    BasketItems.Add(item);
          //    await ReCalculateTotalAsync();
          //}
  
          public ICommand ItemSelectedCommand =&gt; new Command(async () =&gt;
          {
              try
              {
                  WarehouseItemSelected = null;
              }
              catch (Exception ex)
              {
  
              }
  
          });
  
          public string BadgeText
          {
              get
              {
                  return _badgeText;
              }
              set
              {
                  _badgeText = value;
                  RaisePropertyChanged(() =&gt; BadgeText);
              }
          }
  
  
          public ICommand AddtoCartCommand =&gt; new Command(async(e)=&gt; await AddItemAsync(e));
          private async Task AddItemAsync(object e)
          {
              try
              {                 
                  var value = int.Parse(BadgeText);
  
                  if (value &lt; 10)
                  {
  
                      BadgeText = (++value).ToString();
                      //BadgeColor = Color.FromHex("#000000");
                      //await Task.Delay(3000);
                      //BadgeColor = Color.FromHex("#FF9933");
                  }
                  else
                      BadgeText = "0";
  
                  MessagingCenter.Send(this, "ShoppingCartCount", BadgeText);
                  var selectedItem = (ProductDetailsViewModel)e;
  
                  await AddBasketItemAsync(selectedItem);
                  RaisePropertyChanged(() =&gt; BasketItems);
              }
              catch (Exception ex)
              {
                await  App.Current.MainPage.DisplayAlert("Alert!", "Something went wrong!..", "Ok");
              }
          }
  
          public Color BadgeColor
          {
              get
              {
                  return _badgeColor;
              }
              set
              {
                  _badgeColor = value;
                  RaisePropertyChanged(() =&gt; BadgeColor);
              }
          }
          private async Task AddBasketItemAsync(ProductDetailsViewModel selectedItem)
          {
              try
              {
                  // BasketItems.Add(selectedItem); this can be used if BasketItems is of type productdetauilsviewmodel
                  BasketItems.Add(new CartItem { BasketProductId = ProductId, WarehouseDetails = WareHouses });
  
                  await ReCalculateTotalAsync();
              }
              catch (Exception ex)
              {
                await  App.Current.MainPage.DisplayAlert("Alert!", "Something went wrong!..", "Ok");
              }
          }
          private async Task ReCalculateTotalAsync()
          {
              //Total = 0;
  
              //if (BasketItems == null)
              //{
              //    return;
              //}
  
              //foreach (var orderItem in BasketItems)
              //{
              //    Total += (orderItem.Quantity * orderItem.UnitPrice);
              //}
  
              //var authToken = _settingsService.AuthAccessToken;
              //var userInfo = await _userService.GetUserInfoAsync(authToken);
  
              //await _basketService.UpdateBasketAsync(new CustomerBasket
              //{
              //    BuyerId = userInfo.UserId,
              //    Items = BasketItems.ToList()
              //}, authToken);
          }
  
          //public ICommand AddtoCartCommand =&gt; new Command(async () =&gt;
          //{
          //    var value = int.Parse(BadgeText);
  
          //    if (value &lt; 10)
          //        BadgeText = (++value).ToString();
          //    else
          //        BadgeText = "0";
          //    MessagingCenter.Send(this, "ShoppingCartCount", BadgeText);
          //});
          public ObservableCollection&lt;CartItem&gt; BasketItems
          {
              get { return _basketItems; }
              set
              {
                  _basketItems = value;
                  RaisePropertyChanged(() =&gt; BasketItems);
              }
          }
          private int _listHeight;
  
  
          public int ListHeight
          {
              get
              {
                  return _listHeight;
              }
              set
              {
                  _listHeight = value;
                  RaisePropertyChanged(() =&gt; ListHeight);
              }
          }
  
          private WareHouse _warehouseItemSelected;
          public WareHouse WarehouseItemSelected
          {
              get
              {
                  return _warehouseItemSelected;
              }
              set
              {
                  _warehouseItemSelected = value;
                  RaisePropertyChanged(() =&gt; WarehouseItemSelected);
  
  
              }
          }
  
          public class WareHouse
          {
              public int WarehouseId{ get; set; }
              public string WareHouseName { get; set; }
              public int[] Items { get; set; }
              public int quantity { get; set; }
          }
  
          private ObservableCollection&lt;WareHouse&gt; _wareHouses;
          public ObservableCollection&lt;WareHouse&gt; WareHouses
          {
              get
              {
                  return _wareHouses;
              }
              set
              {
                  _wareHouses = value;
                  RaisePropertyChanged(() =&gt; WareHouses);
              }
          }
  
  
  
          public long ProductRating
          {
              get
              {
                  return _productRating;
              }
              set
              {
                  _productRating = value;
                  RaisePropertyChanged(() =&gt; ProductRating);
  
  
              }
          }
          public long ProductId
          {
              get
              {
                  return _productId;
              }
              set
              {
                  _productId = value;
                  RaisePropertyChanged(() =&gt; ProductId);
  
  
              }
          }
  
          public ObservableCollection&lt;string&gt; ProductImage
          {
              get
              {
                  return _productImage;
              }
              set
              {
                  _productImage = value;
                  RaisePropertyChanged(() =&gt; ProductImage);
              }
          }
          public string ProductName
          {
              get
              {
                  return _productName;
              }
              set
              {
                  _productName = value;
                  RaisePropertyChanged(() =&gt; ProductName);
              }
          }
          public long ProductStock
          {
              get
              {
                  return _productStock;
              }
              set
              {
                  _productStock = value;
                  RaisePropertyChanged(() =&gt; ProductStock);
  
  
              }
          }
          public double ProductPrice
          {
              get
              {
                  return _productPrice;
              }
              set
              {
                  _productPrice = value;
                  RaisePropertyChanged(() =&gt; ProductPrice);
  
  
              }
          }
          public string ProductSKU
          {
              get
              {
                  return _productSKU;
              }
              set
              {
                  _productSKU = value;
                  RaisePropertyChanged(() =&gt; ProductSKU);
  
  
              }
          }
          public string OverviewColor
          {
              get
              {
                  return _overviewColor;
              }
              set
              {
                  _overviewColor = value;
                  RaisePropertyChanged(() =&gt; OverviewColor);
  
  
              }
          }
          public string ReviewsColor
          {
              get
              {
                  return _reviewsColor;
              }
              set
              {
                  _reviewsColor = value;
                  RaisePropertyChanged(() =&gt; ReviewsColor);
  
  
              }
          }
          public string ProductDescription
          {
              get
              {
                  return _productDescription;
              }
              set
              {
                  _productDescription = value;
                  RaisePropertyChanged(() =&gt; ProductDescription);
  
  
              }
          }
          public bool ProductDescriptionIsVisible
          {
              get
              {
                  return _productDescriptionIsVisible;
              }
              set
              {
                  _productDescriptionIsVisible = value;
                  RaisePropertyChanged(() =&gt; ProductDescriptionIsVisible);
  
  
              }
          }
  
          private bool _reviewIsVisible;
          public bool ReviewIsVisible
          {
              get
              {
                  return _reviewIsVisible;
              }
              set
              {
                  _reviewIsVisible = value;
                  RaisePropertyChanged(() =&gt; ReviewIsVisible);
  
  
              }
          }
  
          public Command MyCommand { protected set; get; }
          public ICommand AddReviewCommand =&gt; new Command(async () =&gt;
          {
              try
              {
                  // await push.Instance.PopAllAsync();
                  await PopupNavigation.Instance.PushAsync(new ReviewPopUpView());
                  //await _navigation.PushAsync(new ReviewPopUpView());
  
              }
  
              catch (Exception ex)
              {
  
              }
          });
          public ICommand ShareCommand =&gt; new Command(async () =&gt;
          {
              try
              {
                  await CrossShare.Current.Share(new ShareMessage
                  {
                      Text = "Please download RcBazaar app from playstore",
                      Title = "Share Product",
                      Url = "http://rcbazaar.com/product.aspx?productid=6863"
                  });
  
              }
  
              catch (Exception ex)
              {
  
              }
          });
          private void OnRatingChanged()
          {
              try
              {
  
                  //Subscriber listen for the specific message. Here getting data for refresh the listView when add item to the database.
                  MessagingCenter.Subscribe&lt;ProductsView, float&gt;(this, "ProductsPage", (sender, arg) =&gt;
                  {
                      if (arg != null)
                      {
  
                          Rating = arg;
                      }
  
                  });
              }
  
              catch (Exception ex)
              {
  
              }
          }
          private float _rating;
          public float Rating
          {
              get
              {
                  return _rating;
              }
              set
              {
                  _rating = value;
                  RaisePropertyChanged(() =&gt; Rating);
              }
          }
          public ICommand ViewImageCommand =&gt; new Command(async (parameter) =&gt; await ViewImage((string)parameter));
  
          public async Task ViewImage(string ImageName)
          {
              try
              {
  
  
                  await NavigationService.NavigateToAsync&lt;ImageFullScreenViewModel&gt;(ImageName);
  
  
              }
  
              catch (Exception ex)
              {
  
              }
          }
          public ICommand OverviewCommand =&gt; new Command(async () =&gt;
          {
              try
              {
  
  
                  OverviewColor = "#231f20";//blue color
                  ReviewsColor = "#DCDCDC";//lightgray
                  ProductDescriptionIsVisible = true;
                  ReviewIsVisible = false;
  
              }
  
              catch (Exception ex)
              {
  
              }
          });
          public ICommand ReviewsCommand =&gt; new Command(async () =&gt;
          {
              try
              {
                  OverviewColor = "#DCDCDC";//lightgray
                  ReviewsColor = "#231f20";//blue color
  
                  ProductDescriptionIsVisible = false;
                  ReviewIsVisible = true;
  
              }
  
              catch (Exception ex)
              {
  
              }
          });
  
      }
  }
  </code></pre>
  
  <p><strong>Unsubscribing when home page disappears:</strong></p>
  
  <pre><code>   using FFImageLoading.Work;
  using RCBazaar.CustomRenderer;
  using RCBazaar.Helpers;
  using RCBazaar.ViewModels;
  using RCBazaar.Views.NavigationBarWithSideDrawer;
  using Rg.Plugins.Popup.Services;
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  
  using Xamarin.Forms;
  using Xamarin.Forms.Xaml;
  
  namespace RCBazaar.Views
  {
      [XamlCompilation(XamlCompilationOptions.Compile)]
      public partial class HomeView : ContentPage
      {
  
  
          public HomeView()
          {
  
              try
              {
                  InitializeComponent();
  
                  NavigationPage.SetHasNavigationBar(this, false);
  
                  //BindingContext = new HomeProductsViewModel(this.Navigation);
  
              }
              catch (Exception ex)
              {
                  App.Current.MainPage.DisplayAlert(Constants.ConstantKeys.Alert, Constants.ConstantKeys.UIError, Constants.ConstantKeys.Ok);
              }
          }
  
  
          protected override void OnDisappearing()
          {
              base.OnDisappearing();
              MessagingCenter.Unsubscribe&lt;SortingOptionsViewModel&gt;(this, "UpdateHomeList");
              MessagingCenter.Unsubscribe&lt;ProductDetailsViewModel, string&gt;(this, "ShoppingCartCount");
          }
  
          protected override void OnAppearing()
          {
              base.OnAppearing();
              MessagingCenter.Unsubscribe&lt;ProductDetailsViewModel, string&gt;(this, "ShoppingCartCount");
          }
  
      }
  }
  </code></pre>