FlatCache 0.1.0

FlatCache 0.1.0

Maintained by Ryan Nystrom.



FlatCache 0.1.0

  • By
  • Ryan Nystrom

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 'ContextMenu'

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.

struct User {
  let name: String
}

extension User: Cachable {
  var id: 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.

let cache = FlatCache()
let user = User(name: "ryan")
cache.set(user)
if let cached = cache.get(user) as User? {
  print(user.name) // "ryan"
}

FlatCache uses the type information with the get() 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 let's multiple systems respond to object changes.

let cache = FlatCache()
let user = User(name: "ryan")
let listener = 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 a single object or hundreds.

Acknowledgements