Code Monkey home page Code Monkey logo

tinycache's Introduction

TinyCache

Small helper for offline and caching of long-running processes

Build status

buildstatus

Breaking changes in version 2.0

Version 2.0.x will introduce breaking changes to how to use TinyCache. Pre 2.0 we could only have one instance of TinyCache. 2.0 introduces the option to have multiple instances of TinyCache. To make that possible we have introduced TinyCacheHandler.

TinyCacheHandler

If we only want one instance of TinyCache, we can use the Default method of TinyCacheHandler. First time you access the Default property a new instance of TinyCache will be created if there are not instances created. This instance will get default as the key.

Create an additional instance of TinyCache

To add a new instance of TinyCacheHandler we can use either the create method or the add method.

Using the Create method:

var newCache = TinyCacheHandler.Create("myNewCache");

Using the Add method:

var newCache = new TinyCache();
TinyCacheHandler.Add("myNewCache", newCache);

Set default cache

If we have multiple cache instances, we maybe not want the first one to be default, then we can change that by passing the cahce key to the SetDefault method of TinyCacheHandler.

TinyCacheHandler.SetDefault("myNewCache");

Get a specific instance of TinyCache

If we want to get an instance of TinyCache that not are the default instance, we can use the key for the instance as in the code below.

var cache = TinyCacheHandler.Get("myNewCache");

var result = cache.RunAsync<List<Data>>("cachekey", () => { return api.GetData("customdata"); });

Example

Use file storage

Install NuGet package TinyCache.FileStorage.

// Create a cache storage, in memory cache will be the default.
var store = new FileStorage();

var cacheFolder = string.Empty;
            
#if __IOS__ || __MACOS__
            cacheFolder = NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User)[0];
#elif __ANDROID__
            cacheFolder = Application.Context.CacheDir.AbsolutePath;
#elif __UWP__
            cacheFolder = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
#else
            cacheFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
#endif

store.Initialize(cacheFolder);

// Set cache storage
TinyCache.TinyCache.SetCacheStore(store);

// Fetch data with default policy
var result = await TinyCacheHandler.Default.RunAsync<List<Data>>("cachekey", () => { return api.GetData("customdata"); });

Use property storage in Xamarin.Forms

Install NuGet package TinyCache.Forms.

// Create a cache storage, in memory cache will be the default.
var store = new XamarinPropertyStorage();

// Set cache storage
TinyCacheHandler.Default.SetCacheStore(store);

// Fetch data with default policy
var result = await TinyCacheHandler.Default..RunAsync<List<Data>>("cachekey", () => { return api.GetData("customdata"); });

Caching DelegationHandler

AuoRestApi api = new AuoRestApi(apiEndPoint, new NoClientCredentials(), new TinyCache.TinyCacheDelegationHandler());

Some extra examples

Not needed, but nice to have

// Handle errors
TinyCache.TinyCache.OnError += (sender, e) =>
{
    ShowError(e);
};

// Set a base policy that will be used when no policy is specified
TinyCacheHandler.Default..SetBasePolicy(
    new TinyCachePolicy()
        .SetMode(TinyCacheModeEnum.CacheFirst) // fetch from cache first
        .SetFetchTimeout(TimeSpan.FromSeconds(5)) // 5 second excecution limit
        .SetExpirationTime(TimeSpan.FromMinutes(10)) // 10 minute expiration before next fetch
        .SetUpdateCacheTimeout(50) // Wait 50ms before trying to update cache in background
        .UpdateHandler = async (key, newdata) => { await DoStuff(key, newdata); }); // Handle background updates 

// Handle background changes
TinyCacheHandler.Default.OnUpdate += async (object sender, CacheUpdatedEvt e) => {
    var cacheKey = e.Key;
    var dataObject = e.Value;
    async HandleObjectChange(cacheKey,dataObject as MyDataType);
};

Some extra for preloading cache

Not needed, but nice to have

// Get all cached data from storage (to be saved in static file in project and then loaded)
var preloadString = store.GetAllAsLoadableString();

// Preload cache if needed from stored string:
store.LoadFromString(CacheResources.PreloadData.JsonData);

tinycache's People

Contributors

dhindrik avatar johankson avatar matst80 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.