Improve Xamarin Forms App UX by Data Caching

When developing a mobile app persisting data is important, why? Because a mobile app is not a web app, it shouldn’t depend on having a reliable internet connection 100% of the time. For example, when you open a mobile app to see the list of transactions if you don’t have internet you will only see an empty screen with “There is no internet connection error” message. Won’t it be a better user experience if you could see the latest data cached?

In Xamarin Forms there are some options we can use to do data caching:

  • Use a local database like SQLite or Realm
  • Use a caching library for basic use cases.

In this article, I’m going to show you how to do data caching by using the Monkey-Cache library by James Montemagno.

Let’s explore MonkeyCache

” The goal of Monkey Cache is to enable developers to easily cache any data for a limited amount of time.”

Setup

Barrel.ApplicationId = “your_unique_name_here”;

Save data

Barrel.Current.Add(key, data, expireIn);

Retrieve data

Barrel.Current.Get<Type of Data you want to get>(url);

Remove data

Barrel.Current.EmptyAll();

Let’s use it

1.Install the MonkeyCache.FileStore package

2.Create an ApiManager class to handle your requests and assign an ApplicationId to the cache library

3.Send the API request and store in cache the data response

If there’s no internet connection and the data cached has not expired the method will return the data in the cache, if not it will do an API request and will store the JSON response by using the MonkeyCache library.

Extra libraries used:

NOTE: If you want to see better options to show the internet connection error message, you can check this article.

4.Call the service in your ViewModel

5.Show the elements in your XAML

The result:

That’s all for now! If you want to know more information about this great library, you can check more information here.

Check the full source code here.

Happy coding!

You may also like

2 Comments