Search code examples
swiftsiesta-swift

Is it possible to specify a cache policy?


Is it possible in Siesta to use a cache policy like:

  • LocalOnly
  • NetworkFirst

Where LocalOnly is getting the data from the local cache only, and NetworkFirst is getting the data from the network, and if it fails, retrieve from local cache.


Solution

  • @nikano’s answer is correct if you want to control the cache behavior of URLSession when using it as Siesta’s underlying networking library.

    In general, Siesta lets the underlying networking do its thing. Options valid for URLSession remain the same even when you use it with Siesta.


    Siesta itself is an observable in-memory cache. One of its core design features is that it gives you fine-grained control over which data you see, cached or fresh — and that crucially is not an either/or question. You can use both.

    If you want to see the data cached locally in memory, your “local only,” just ask a resource for it:

    resource.latestData
    

    If you want to force a network request even if there is cached data, i.e. your “network only:”

    resource.load().onSuccess { ...use the data... }
    

    …and if for some reason you want to request up-to-date data but not have Siesta cache it:

    resource.request(.get).onSuccess { ... }
    

    However, the most common idiom is to use both the cached and fresh data:

    resource.addObserver(somethingObserverThatUsesTheData)
    resource.loadIfNeeded()
    

    In that case, somethingObserverThatUsesTheData first sees the locally cached data (if any), then sees the data that comes back from the network library (if there was a network request).


    Note that the data that comes back from the network library might itself be cached. In most situations, I recommend disabling URLSession’s cache so that you know you are getting up-to-date data. However, having two layers of caching might be the right thing in some circumstances.