MonkeyCache step by step

The amazing James Montemagno of Xamarin/Microsoft has done it again. He has created an incredibly simple cache, named MonkeyCache, that you can get up and running very quickly.

In this post I will walk through setting up and using the cache, step by step.

To get started, create a new project in Visual Studio or Visual Studio Mac. Choose Shell or with the latest Visual Studio Windows choose FlyOut.

Run the program and see what it does. Pay special attention to creating a new item and to the about page.

Click on the Solution Explorer and open NuGet. Go to Browse and browse for MonkeyCache. The simple library will come up and then three for different storage types: file-based, SQLite or LiteDB:

For this demo, I’ll select FileStore.

Open App.xaml.cs and go to the App() method. Add the following line which must come before any other method calls:

Barrel.ApplicationId = "MonkeyCacheDemo";

You can put any value for the ID. You are now all set up.

MonkeyCache works on the premise that you have exactly one barrel at your disposal, and you throw everything you want to cache into that barrel. When you want to extract from the cache you ask the barrel for your cached item. Let’s see that in action.

In NewItemViewModel a new Item object is put into the DataStore. Let’s also add it to the cache (just for demonstration purposes)

Barrel.Current.Add("FirstItem",newItem,expireIn:TimeSpan.FromHours(1));

That’s all it takes to add the Item object to the cache. Let’s take this line apart. First you call Barrel.Current.Add to add an item to the Barrel. You pass in an arbitrary string which becomes the key for later retrieving the item.

You then pass whatever it is that you want to cache (in our case newItem)

Finally, you pass in when you want the time to expire (in this case in one hour). When an item expires it is not deleted, but you can test for expiration and treat the data as unusable if it has expired.

You can delete items from the cache with one of these three commands:

Barrel.Current.Empty(key: );
Barrel.Current.EmptyAll
Barrel.Current.EmptyExpired

As you might have guessed, the first one empties the barrel of one cached item based on its key (in our case “FirstItem”). EmptyAll clears out the cache, and EmptyExpired rids the cache of all expired items.

In any case, we now have an Item in our cache with the key “FirstItem” which will expire in one hour.

I’d like to extract that item from the cache and use it in AboutPage.xaml. To do so, let’s make a minor modification to AboutPage.xaml. We’ll put a StackLayout just before the Grid. (Actually we’ll need two StackLayouts, one encompassing the new StackLayout and the grid together). We’ll mark our new StackLayout as Orientation=”Horizontal” and we’ll put in two labels (side by side):

<StackLayout Orientation="Horizontal">
    <Label 
    Text="{Binding FromCache.Text}" 
    BackgroundColor="Black" 
    TextColor="White"
    FontSize="20"
    FontAttributes="Bold"/>
    
    <Label 
    Text="{Binding FromCache.Description}" 
    BackgroundColor="Black" 
    TextColor="White"
    FontSize="20"
    FontAttributes="Bold"/>
</StackLayout>

Notice that they both bind to properties of a ViewModel property named FromCache. FromCache is an Item, as we’ll see in just a moment.

The intent here is pretty clear, we’ll retrieve the Item from the cache, and display its Text and Description values in these two labels.

Let’s go to the ViewModel. The first thing we need is the FromCache property, which is of type Item:

 private Item _fromCache;
 public Item FromCache
 {
     get => _fromCache;
     set => SetProperty(ref _fromCache, value);
 }

Next we want to get the cached value and put it into this property. I’ll do that in a method called UpdateFromBarrel:

 public void UpdateFromBarrel()
 {
     if (!Barrel.Current.IsExpired(key: "FirstItem"))
     {
         FromCache = Barrel.Current.Get<Item>(key: "FirstItem");
     }
 }

Here we first check to see if our Item has expired (using the same key: “FirstItem”). If it has not, we extract our Item using Barrel.Current.Get setting the type of object we are retrieving (Item) and they key for that Item (“FirstTime”) and we assign that to our FromCache property.

One more thing. I want to be able to control when UpdateFromBarrel is called, so I’ll add a button to AboutPage.xaml:

 <Button Text="Update from Cache"
         Command="{Binding UpdateFromCacheCommand}" />

And implement the command in the ViewModel:

UpdateFromCacheCommand = new Command(() => UpdateFromBarrel());

Don’t forget to declare the command:

public ICommand UpdateFromCacheCommand { get; }

That’s it. Now when you add an item it will be added to the cache (thrown in the barrel) and when you go to About and press the UpdateFromCache button, it will be extracted and displayed (title and description)

Item Save
About Page after retrieving from cache

Full source code is here

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Essentials and tagged , . Bookmark the permalink.