SpaceMonkey
SpaceMonkey

Reputation: 4365

Memory used by pushing a lot of pages on Xamarin.Forms' NavigationPage

I have a Xamarin.Forms NavigationPage and I noticed that after pushing quite a lot of pages (say 20), the app starts being laggy and might freeze at some point. I'm guessing it must be using a lot of memory (I should really check in Android's monitoring tools now that I thought about it).

Is there another way I can provide a history functionality (so, the user can always press back to go to where they were reading before) that doesn't eat up all the memory? I know it's possible because it's done in other apps.

Upvotes: 0

Views: 877

Answers (1)

Daniel Luberda
Daniel Luberda

Reputation: 7454

For solutions with multiple pages and large navigation stack You could use PagesFactory:

public static class PagesFactory
{
    static readonly Dictionary<Type, Page> pages = new Dictionary<Type, Page>();

    static NavigationPage navigation;
    public static NavigationPage GetNavigation()
    {
        if (navigation == null)
        {
            navigation = new NavigationPage(PagesFactory.GetPage<Views.MainMenuView>());
        }
        return navigation;
    }

    public static T GetPage<T>(bool cachePages = true) where T : Page
    {
        Type pageType = typeof(T);

        if (cachePages)
        {
            if (!pages.ContainsKey(pageType))
            {
                Page page = (Page)Activator.CreateInstance(pageType);
                pages.Add(pageType, page);
            }

            return pages[pageType] as T;
        }
        else
        {
            return Activator.CreateInstance(pageType) as T;
        }
    }

    public static async Task PushAsync<T>() where T : Page
    {
        await GetNavigation().PushAsync(GetPage<T>());
    }

    public static async Task PopAsync()
    {
        await GetNavigation().PopAsync();
    }

    public static async Task PopToRootAsync()
    {
        await GetNavigation().PopToRootAsync();
    }

    public static async Task PopThenPushAsync<T>() where T : Page
    {
        await GetNavigation().PopAsync();
        await GetNavigation().PushAsync(GetPage<T>());
    }
}

Upvotes: 2

Related Questions