+ Users expect their UI experience to never be compromised (blocked) by new data loads. Whether an application is social, news, or business-to-business, users expect a seamless experience both online and offline.
+ International users expect minimal data downloads as many megabytes of downloaded data can quickly result in astronomical phone bills.
A Store is a class that simplifies fetching, parsing, storage, and retrieval of data in your application. A Store is similar to the Repository pattern [[https://msdn.microsoft.com/en-us/library/ff649690.aspx](https://msdn.microsoft.com/en-us/library/ff649690.aspx)] while exposing an API built with [Coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html) that adheres to a unidirectional data flow.
A Store is responsible for managing a particular data request. When you create an implementation of a Store, you provide it with a `Fetcher`, a function that defines how data will be fetched over network. You can also define how your Store will cache data in-memory and on-disk, as well as how to parse it. Since Store returns your data as an `Observable`, threading is a breeze! Once a Store is built, it handles the logic around data flow, allowing your views to use the best data source and ensuring that the newest data is always available for later offline use. Stores can be customized to work with your own implementations or use our included middleware.
Store leverages RxJava and multiple request throttling to prevent excessive calls to the network and disk cache. By utilizing Store, you eliminate the possibility of flooding your network with the same request while adding two layers of caching (memory and disk).
Starting with Store 3.0, `retrolambda` is no longer used. Therefore to allow support for lambdas the Java `sourceCompatibility` and `targetCompatibility` need to be set to `1.8`
You create a Store using a builder. The only requirement is to include a `Fetcher<ReturnType, KeyType>` that returns a `Single<ReturnType>` and has a single method `fetch(key)`
Stores use generic keys as identifiers for data. A key can be any value object that properly implements `toString()`, `equals()` and `hashCode()`. When your `Fetcher` function is called, it will be passed a particular Key value. Similarly, the key will be used as a primary identifier within caches (Make sure to have a proper `hashCode()`!!).
The first time you subscribe to `store.get(barCode)`, the response will be stored in an in-memory cache. All subsequent calls to `store.get(barCode)` with the same Key will retrieve the cached version of the data, minimizing unnecessary data calls. This prevents your app from fetching fresh data over the network (or from another external data source) in situations when doing so would unnecessarily waste bandwidth and battery. A great use case is any time your views are recreated after a rotation, they will be able to request the cached data from your Store. Having this data available can help you avoid the need to retain this in the view layer.
In the New York Times app, overnight background updates use `fetch()` to make sure that calls to `store.get()` will not have to hit the network during normal usage. Another good use case for `fetch()` is when a user wants to pull to refresh.
For real-time updates, you may also call `store.stream()` which returns an `Observable` that emits each time a new item is added to the Store. You can think of stream as an Event Bus-like feature that allows you to know when any new network hits happen for a particular Store. You can leverage the Rx operator `filter()` to only subscribe to a subset of emissions.
There is another special way to subscribe to a Store: `getRefreshing(key)`. This method will subscribe to `get()` which returns a single response, but unlike `get()`, `getRefreshing(key)` will stay subscribed. Anytime you call `store.clear(key)` anyone subscribed to `getRefreshing(key)` will resubscribe and force a new network response.
To prevent duplicate requests for the same data, Store offers an inflight debouncer. If the same request is made within a minute of a previous identical request, the same response will be returned. This is useful for situations when your app needs to make many async calls for the same data at startup or when users are obsessively pulling to refresh. As an example, The New York Times news app asynchronously calls `ConfigStore.get()` from 12 different places on startup. The first call blocks while all others wait for the data to arrive. We have seen a dramatic decrease in the app's data usage after implementing this inflight logic.
Since it is rare for data to arrive from the network in the format that your views need, Stores can delegate to a parser by using a `StoreBuilder.<BarCode, BufferedSource, Article>parsedWithKey()`
There are also separate middleware libraries with parsers to help in cases where your fetcher is a `Reader`, `BufferedSource` or `String` and your parser is Gson:
Stores can enable disk caching by passing a `Persister` into the builder. Whenever a new network request is made, the Store will first write to the disk cache and then read from the disk cache.
Stores don’t care how you’re storing or retrieving your data from disk. As a result, you can use Stores with object storage or any database (Realm, SQLite, CouchDB, Firebase etc). The only requirement is that data must be the same type when stored and retrieved as it was when received from your `Fetcher`. Technically, there is nothing stopping you from implementing an in memory cache for the “persister” implementation and instead have two levels of in memory caching--one with inflated and one with deflated models, allowing for sharing of the “persister” cache data between stores.
**Note**: When using a Parser and a disk cache, the Parser will be called AFTER fetching from disk and not between the network and disk. This allows your persister to work on the network stream directly.
If using SQLite we recommend working with [SqlBrite](https://github.com/square/sqlbrite). If you are not using SqlBrite, an `Observable` can be created rather simply with `Observable.fromCallable(() -> getDBValue())`
We've found the fastest form of persistence is streaming network responses directly to disk. As a result, we have included a separate library with a reactive FileSystem which depends on Okio `BufferedSource`s. We have also included a `FileSystemPersister` which will give you disk caching and works beautifully with `GsonSourceParser`. When using the `FileSystemPersister` you must pass in a `PathResolver` which will tell the file system how to name the paths to cache entries.
+ Ability to be notified and resubscribed when caches are cleared (helpful for times when you need to do a POST request and update another screen, such as with `getRefreshing()`)
We recommend using the above builder setup for most Stores. The SourcePersister implementation has a tiny memory footprint because it will stream bytes from network to disk and then from disk to parser. The streaming nature of Stores allows us to download dozens of 1mb+ json responses without worrying about OOM on low-memory devices. As mentioned above, Stores allow us to do things like calling `configStore.get()` a dozen times asynchronously before our Main Activity finishes loading without blocking the main thread or flooding our network.
If you'd like your Store to know about disk data staleness, you can have your `Persister` implement `RecordProvider`. After doing so you can configure your Store to work in one of two ways:
`networkBeforeStale()` - Store will try to get network source when disk data is stale. If the network source throws an error or is empty, stale disk data will be returned.
+ **File System** Persistence Library built using [Okio](https://github.com/square/okio) Source/Sink + Middleware for streaming from Network to FileSystem
See the app for example usage of Store. Alternatively, the [Wiki](https://github.com/NYTimes/Store/wiki) contains a set of recipes for common use cases
+ https://github.com/stoyicker/master-slave-clean-store: An offline-first Master-Slave project with scroll-driven pagination using Store for the data layer.
+ https://github.com/benoberkfell/cat-rates: [Ben Oberkfell's 360AnDev talk, "Android Architecture for the Subway"](https://academy.realm.io/posts/360-andev-2017-ben-oberkfell-android-architecture-offline-first/) illustrates using Store for caching server responses