0

I was wondering if there is a way to null binding contexts of all viewmodels and then garbage collect on logout? In my application

async void OnLogoutClicked(object sender, EventArgs args)
        {
            try
            {
                var result = await UserLogoutRequest.Logout();

                if (result.responseCode == ResponseCodes.SUCCESS)
                {
                    DialogService.ShowSuccessToast("Logout successful");
                }
                else
                {
                    DialogService.ShowErrorToast("A server error occurred during logout");
                }
            }
            catch (Exception ex)
            {
                DialogService.ShowErrorToast("A client error occurred during logout");
            }
            finally
            {
                await DataManager.Instance.SetLoggedInUser(null);
                await DataManager.Instance.SetToken(string.Empty);
                GC.Collect(); // TODO: Figure out how to GC the ViewModels so that when user logs in again it's not using the same instance of the VM
                await AppShell.Current.GoToAsync("//Welcome");
            }
        }
    }

The GC.Collect() does not seem to do much since the pages are still linked to their viewmodels. I guess I could do BindingContext = null in the OnDisappearing of the pages, but I feel that the OnDisappearing gets called too often. I would prefer to just null the BindingContext of all pages on logout and then garbage collect, but there doesn't seem to be any hook for me to do that.

Thanks in advance.

Philip
  • 638
  • 1
  • 8
  • 22
  • 1
    @Philp I search some info, and find there are two ways to call GC.Collect(), one is to call GC.Collect() in OnDisappearing method [Shell possible memory leak](https://github.com/xamarin/Xamarin.Forms/issues/7703), another is to call GC.Collect() when the page is Popped of the stack[How often doe you call GC.Collect](https://forums.xamarin.com/discussion/61853/how-often-doe-you-call-gc-collect) – Cherry Bu - MSFT May 27 '20 at 02:17
  • Thanks @CherryBu-MSFT. Do you know if OnPopped gets called in Xamarin Shell? – Philip May 27 '20 at 12:54
  • `OnPopped` here means when you navigating to the last page . – Lucas Zhang May 29 '20 at 15:10

0 Answers0