Skip to content

Repository files navigation

FlatCache

Store any object in a flat cache by String id and notify listeners when changes occur.

This is an implementation of Soroush Khanlou's The Flat Cache blog post used in GitHawk.

Installation

Just add FlatCache to your Podfile and pod install. Done!

pod 'FlatCache'

Usage

Add the Cachable protocol to models that you want to store in the cache. Conform to the protocol by returning a String identifier used for lookup.

structUser{letname:String}extensionUser:Cachable{varid:String{return name
}}

Don't worry about id collisions between objects. The cache "namespaces" different models by type.

Now just create a FlatCache object and start reading & writing with it.

letcache=FlatCache()letuser=User(name:"ryan")
cache.set(value: user)iflet cached = cache.get(id: user.id)asUser?{print(cached.name) // "ryan"
}

FlatCache uses the type information with the get(id:) function to lookup the appropriate object. You must type the result somehow.

Listeners

One of the strengths of FlatCache is adding "listeners" to the cache to be notified when an object is changed. This powerful tool lets multiple systems respond to object changes.

letcache=FlatCache()letuser=User(name:"ryan")letlistener=MyUserListener()
cache.add(listener: listener, value: user)

Now whenever user is set again in the cache, MyUserListener will be notified with the following function:

func flatCacheDidUpdate(cache:FlatCache, update:FlatCache.Update){switch update {case.item(let item):
// just a single object updated
case .list:
// a list of subscribed objects updated
}}

FlatCache coalesces so only a single event is delivered when something changes, no matter if an update has just a single object or hundreds.

Acknowledgements

About

Implementation of Soroush Khanlou's Flat Cache.

Topics

Resources

Stars

171 stars

Watchers

3 watching

Forks

Releases

Packages

Contributors

Languages