Coder Social home page Coder Social logo

akavache's Introduction

Akavache: An Asynchronous Key-Value Store for Native Applications

Akavache is an asynchronous, persistent key-value cache created for writing native desktop and mobile applications in C#. Think of it like memcached for desktop apps.

What does that mean?

Downloading and caching remote data from the internet while still keeping the UI responsive is a task that nearly every modern native application needs to do. However, many applications that don't take the consideration of caching into the design from the start often end up with inconsistent, duplicated code for caching different types of objects.

Akavache is a library that makes common app patterns easy, and unifies caching of different object types (i.e. HTTP responses vs. JSON objects vs. images).

It's built on a core key-value byte array store (conceptually similar to a Dictionary<string, byte[]>), and on top of that store, extensions are added to support:

  • Arbitrary objects via JSON
  • HTTP Requests
  • Fetching and loading Images
  • Securely storing User Credentials

Getting Started

Interacting with Akavache is primarily done through an object called BlobCache. At App startup, you must first set your app's name via BlobCache.ApplicationName - on the desktop, your application's data will be stored in %AppData%\[ApplicationName] and %LocalAppData%\[ApplicationName]. Store data that should be shared between different machines in BlobCache.UserAccount and store data that is throwaway or per-machine (such as images) in BlobCache.LocalMachine.

The most straightforward way to use Akavache is via the object extensions:

var myToaster = new Toaster();
BlobCache.UserAccount.InsertObject("toaster", myToaster);

//
// ...later, in another part of town...
//

// Using async/await
var toaster = await BlobCache.UserAccount.GetObjectAsync("toaster");

// or without async/await
Toaster toaster;

BlobCache.UserAccount.GetObjectAsync("toaster")
    .Subscribe(x => toaster = x, ex => Console.WriteLine("No Key!"))

Handling Errors

When a key is not present in the cache, GetObject throws a KeyNotFoundException (or more correctly, OnError's the IObservable). Often, you would want to return a default value instead of failing:

var toaster = await BlobCache.UserAccount.GetObjectAsync("toaster")
    .Catch(Observable.Return(new Toaster()));

Examining Akavache caches

Using Akavache Explorer, you can dig into Akavache repos for debugging purposes to see what has been stored.

Unit Testing with Akavache

By default, if Akavache detects that it is being run in a unit test runner, it will use the TestBlobCache implementation instead of the default implementation. TestBlobCache implements IBlobCache in memory synchronously using a Dictionary instead of persisting to disk.

This class can be explicitly created as well, and initialized to have specific contents to test cache hit / cache miss scenarios. Use the TestBlobCache.OverrideGlobals method to temporarily replace the BlobCache.UserAccount variables with a specific TestBlobCache.

Testing expiration can also be done, using Rx's TestScheduler:

[Fact]
public void TestSomeExpirationStuff()
{
    (new TestScheduler()).With(sched => {
        using (cache = TestBlobCache.OverrideGlobals(null, sched)) {
            cache.Insert("foo", new byte[] { 1,2,3 }, TimeSpan.FromMilliseconds(100));

            sched.AdvanceByMs(50);

            var result = cache.GetAsync("foo").First();
            Assert.Equal(1, result[0]);

            // Fast forward to t=200ms, after the cache entry is expired
            sched.AdvanceByMs(150);

            bool didThrow;
            try {
                // This should now throw KeyNotFoundException
                result = cache.GetAsync("foo").First();
                didThrow = false;
            } catch (Exception ex) {
                didThrow = true;
            }

            Assert.True(didThrow);
        }
    });
}

akavache's People

Contributors

anaisbetts avatar aroben avatar haacked avatar jack-pappas avatar schacon avatar tclem avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.