Store/README.md

295 lines
15 KiB
Markdown
Raw Normal View History

# Store 4
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.dropbox.mobile.store/store4/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.dropbox.mobile.store/store4/)
2017-01-04 19:17:53 +00:00
2020-02-14 10:59:31 +00:00
[![codecov](https://codecov.io/gh/dropbox/Store/branch/master/graph/badge.svg)](https://codecov.io/gh/dropbox/Store)
2020-02-19 01:12:07 +00:00
Store is a Kotlin library for loading data from remote and local sources.
2017-01-04 19:17:53 +00:00
### The Problems:
+ Modern software needs data representations to be fluid and always available.
2019-12-23 17:31:37 +00:00
+ 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.
2017-01-04 19:17:53 +00:00
A Store is a class that simplifies fetching, sharing, 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) while exposing an API built with [Coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html) that adheres to a unidirectional data flow.
2017-01-04 19:17:53 +00:00
Store provides a level of abstraction between UI elements and data operations.
2017-01-04 19:17:53 +00:00
### Overview
2019-12-23 17:31:37 +00:00
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. Since Store returns your data as a `Flow`, 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.
2017-01-04 19:17:53 +00:00
Store leverages 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) as well as ability to add disk as a source of truth where you can modify the disk directly without going through Store (works best with databases that can provide observables sources like [Jetpack Room](https://developer.android.com/jetpack/androidx/releases/room), [SQLDelight](https://github.com/cashapp/sqldelight) or [Realm](https://realm.io/products/realm-database/))
2017-01-04 19:17:53 +00:00
### How to include in your project
Artifacts are hosted on **Maven Central**.
###### Latest version:
2019-12-23 17:31:37 +00:00
```groovy
2021-05-06 17:06:13 +00:00
def store_version = "4.0.1"
//if using kotlin 1.5 (https://github.com/dropbox/Store/issues/263)
2021-12-08 18:59:41 +00:00
def store_version = "4.0.4-KT15"
```
###### Add the dependency to your `build.gradle`:
```groovy
implementation "com.dropbox.mobile.store:store4:${store_version}"
```
###### Set the source & target compatibilities to `1.8`
2019-12-23 17:31:37 +00:00
```groovy
android {
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
...
}
```
2017-01-04 19:17:53 +00:00
### Fully Configured Store
Let's start by looking at what a fully configured Store looks like. We will then walk through simpler examples showing each piece:
2019-11-05 02:11:07 +00:00
```kotlin
StoreBuilder
.from(
Yigit/move fetcher factories to fetcher (#168) (#181) * Move Fetcher factories into companion Fetcher factories were global methods, which made them hard to discover since IDE cannot easily auto-complete. This PR moves them into the companion of Fetcher while also making Fetcher a real interface instead of a typealias. Even though it is a bit more code for the developer, now they can easily discover how to create a Fetcher by typing Fetcher. Fixes: #167 * make rx methods start w/ from too for consistency * Rename fether factories to be more clear, hopefully :/ * remove fetch method, use invoke instead * Make Fetcher.from the one that receives a suspend fun. Create Fetcher.fromFlow for the flowing version. Rename both SourceOfTruth builder methods to . Rely on param names to disambiguate * use .of instead, this seems better to me. We should probably get rid of StoreBuilder.from and make it Store.builder() * fix jvm name for SourceOfTruth.of with flow function * fix RxSourceOfTruth name to match original class * specify bounds for FactoryFetcher * updates per PR review * update graph per SoT rename * update rxjava3 APIs as well These appeared after i rebased, missed them completely. Also fixed some tests, appearantly IJ parameter name refactor does not always work * supress wrong unnecessary cast warning without this, multicaster cannot resolve to the base StoreResponse type * upgade gradle, try to fix build by disabling caching * split subscribers * resubscribe Co-authored-by: miken <miken@dropbox.com> Co-authored-by: miken <miken@dropbox.com>
2020-06-19 10:00:50 +00:00
fetcher = Fetcher.of { api.fetchSubreddit(it, "10").data.children.map(::toPosts) },
sourceOfTruth = SourceOfTruth.of(
reader = db.postDao()::loadPosts,
writer = db.postDao()::insertPosts,
delete = db.postDao()::clearFeed,
deleteAll = db.postDao()::clearAllFeeds
)
).build()
2017-01-04 19:17:53 +00:00
```
With the above setup you have:
+ In-memory caching for rotation
+ Disk caching for when users are offline
+ Throttling of API calls when parallel requests are made for the same resource
+ Rich API to ask for data whether you want cached, new or a stream of future data updates.
2017-01-04 19:17:53 +00:00
And now for the details:
### Creating a Store
You create a Store using a builder. The only requirement is to include a `Fetcher` which is just a `typealias` to a function that returns a `Flow<FetcherResult<ReturnType>>`.
2017-01-04 19:17:53 +00:00
2019-11-05 02:11:07 +00:00
```kotlin
2020-01-10 16:01:56 +00:00
val store = StoreBuilder
Yigit/move fetcher factories to fetcher (#168) (#181) * Move Fetcher factories into companion Fetcher factories were global methods, which made them hard to discover since IDE cannot easily auto-complete. This PR moves them into the companion of Fetcher while also making Fetcher a real interface instead of a typealias. Even though it is a bit more code for the developer, now they can easily discover how to create a Fetcher by typing Fetcher. Fixes: #167 * make rx methods start w/ from too for consistency * Rename fether factories to be more clear, hopefully :/ * remove fetch method, use invoke instead * Make Fetcher.from the one that receives a suspend fun. Create Fetcher.fromFlow for the flowing version. Rename both SourceOfTruth builder methods to . Rely on param names to disambiguate * use .of instead, this seems better to me. We should probably get rid of StoreBuilder.from and make it Store.builder() * fix jvm name for SourceOfTruth.of with flow function * fix RxSourceOfTruth name to match original class * specify bounds for FactoryFetcher * updates per PR review * update graph per SoT rename * update rxjava3 APIs as well These appeared after i rebased, missed them completely. Also fixed some tests, appearantly IJ parameter name refactor does not always work * supress wrong unnecessary cast warning without this, multicaster cannot resolve to the base StoreResponse type * upgade gradle, try to fix build by disabling caching * split subscribers * resubscribe Co-authored-by: miken <miken@dropbox.com> Co-authored-by: miken <miken@dropbox.com>
2020-06-19 10:00:50 +00:00
.from(Fetcher.ofFlow { articleId -> api.getArticle(articleId) }) // api returns Flow<Article>
.build()
2017-01-04 19:17:53 +00:00
```
Store uses 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()`!!).
2017-01-04 19:17:53 +00:00
2019-12-23 17:31:37 +00:00
Note: We highly recommend using built-in types that implement `equals` and `hashcode` or Kotlin `data` classes for complex keys.
### Public Interface - Stream
The primary function provided by a `Store` instance is the `stream` function which has the following signature:
2019-11-05 02:11:07 +00:00
```kotlin
fun stream(request: StoreRequest<Key>): Flow<StoreResponse<Output>>
```
Each `stream` call receives a `StoreRequest` object, which defines which key to fetch and which data sources to utilize.
The response is a `Flow` of `StoreResponse`. `StoreResponse` is a Kotlin sealed class that can be either
a `Loading`, `Data` or `Error` instance.
Each `StoreResponse` includes an `origin` field which specifies where the event is coming from.
2017-01-04 19:17:53 +00:00
* The `Loading` class only has an `origin` field. This can provide you information like "network is fetching data", which can be a good signal to activate the loading spinner in your UI.
* The `Data` class has a `value` field which includes an instance of the type returned by `Store`.
2019-12-23 17:31:37 +00:00
* The `Error` class includes an `error` field that contains the exception thrown by the given `origin`.
2017-01-04 19:17:53 +00:00
2020-01-10 16:01:56 +00:00
When an error happens, `Store` does not throw an exception, instead, it wraps it in a `StoreResponse.Error` type which allows `Flow` to continue so that it can still receive updates that might be triggered by either changes in your data source or subsequent fetch operations.
2017-01-04 19:17:53 +00:00
2019-11-05 02:11:07 +00:00
```kotlin
2020-11-30 19:37:12 +00:00
viewModelScope.launch {
store.stream(StoreRequest.cached(key = key, refresh=true)).collect { response ->
when(response) {
is StoreResponse.Loading -> showLoadingSpinner()
is StoreResponse.Data -> {
if (response.origin == ResponseOrigin.Fetcher) hideLoadingSpinner()
updateUI(response.value)
}
is StoreResponse.Error -> {
if (response.origin == ResponseOrigin.Fetcher) hideLoadingSpinner()
showError(response.error)
}
}
}
}
2017-01-04 19:17:53 +00:00
```
For convenience, there are `Store.get(key)` and `Store.fresh(key)` extension functions.
2017-01-04 19:17:53 +00:00
* `suspend fun Store.get(key: Key): Value`: This method returns a single value for the given key. If available, it will be returned from the in memory cache or the sourceOfTruth. An error will be thrown if no value is available in either the `cache` or `sourceOfTruth`, and the `fetcher` fails to load the data from the network.
* `suspend fun Store.fresh(key: Key): Value`: This method returns a single value for the given key that is obtained by querying the fetcher. An error will be thrown if the `fetcher` fails to load the data from the network, regardless of whether any value is available in the `cache` or `sourceOfTruth`.
2017-01-04 19:17:53 +00:00
```kotlin
2020-01-10 16:01:56 +00:00
lifecycleScope.launchWhenStarted {
val article = store.get(key)
updateUI(article)
2020-01-10 16:01:56 +00:00
}
```
2017-01-04 19:17:53 +00:00
The first time you call to `suspend store.get(key)`, the response will be stored in an in-memory cache and in the sourceOfTruth, if provided.
All subsequent calls to `store.get(key)` 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.
2017-01-04 19:17:53 +00:00
By default, 100 items will be cached in memory for 24 hours. You may [pass in your own memory policy to override the default policy](#Configuring-In-memory-Cache).
2017-01-04 19:17:53 +00:00
2020-11-30 19:37:12 +00:00
### Skipping Memory/Disk
2017-01-04 19:17:53 +00:00
Alternatively, you can call `store.fresh(key)` to get a `suspended result` that skips the memory (and optional disk cache).
2017-01-04 19:17:53 +00:00
A good use case is overnight background updates use `fresh()` to make sure that calls to `store.get()` will not have to hit the network during normal usage. Another good use case for `fresh()` is when a user wants to pull to refresh.
2017-01-04 19:17:53 +00:00
Calls to both `fresh()` and `get()` emit one value or throw an error.
2017-01-04 19:17:53 +00:00
### Stream
2019-12-23 17:31:37 +00:00
For real-time updates, you may also call `store.stream()` which returns a `Flow<T>` that emits each time a new item is returned from your store. You can think of stream as a way to create reactive streams that update when you db or memory cache updates
2019-11-05 02:11:07 +00:00
example calls:
```kotlin
lifecycleScope.launchWhenStarted {
store.stream(StoreRequest.cached(3, refresh = false)) //will get cached value followed by any fresh values, refresh will also trigger network call if set to `true` even if the data is available in cache or disk.
2020-01-10 16:01:56 +00:00
.collect {}
store.stream(StoreRequest.fresh(3)) //skip cache, go directly to fetcher
2020-01-10 16:01:56 +00:00
.collect {}
2019-11-05 02:11:07 +00:00
}
2017-01-04 19:17:53 +00:00
```
2019-11-05 02:11:07 +00:00
### Inflight Debouncer
2019-11-05 02:11:07 +00:00
To prevent duplicate requests for the same data, Store offers an inflight debouncer. If the same request is made as a previous identical request that has not completed, 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.
2017-01-04 19:17:53 +00:00
### Disk as Cache
2017-01-04 19:17:53 +00:00
Stores can enable disk caching by passing a `SourceOfTruth` 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.
2017-01-04 19:17:53 +00:00
### Disk as Single Source of Truth
Providing `sourceOfTruth` whose `reader` function can return a `Flow<Value?>` allows you to make Store treat your disk as source of truth.
Any changes made on disk, even if it is not made by Store, will update the active `Store` streams.
2017-01-04 19:17:53 +00:00
This feature, combined with persistence libraries that provide observable queries ([Jetpack Room](https://developer.android.com/jetpack/androidx/releases/room), [SQLDelight](https://github.com/cashapp/sqldelight) or [Realm](https://realm.io/products/realm-database/))
allows you to create offline first applications that can be used without an active network connection while still providing a great user experience.
2017-01-04 19:17:53 +00:00
2019-11-05 02:11:07 +00:00
```kotlin
StoreBuilder
.from(
Yigit/move fetcher factories to fetcher (#168) (#181) * Move Fetcher factories into companion Fetcher factories were global methods, which made them hard to discover since IDE cannot easily auto-complete. This PR moves them into the companion of Fetcher while also making Fetcher a real interface instead of a typealias. Even though it is a bit more code for the developer, now they can easily discover how to create a Fetcher by typing Fetcher. Fixes: #167 * make rx methods start w/ from too for consistency * Rename fether factories to be more clear, hopefully :/ * remove fetch method, use invoke instead * Make Fetcher.from the one that receives a suspend fun. Create Fetcher.fromFlow for the flowing version. Rename both SourceOfTruth builder methods to . Rely on param names to disambiguate * use .of instead, this seems better to me. We should probably get rid of StoreBuilder.from and make it Store.builder() * fix jvm name for SourceOfTruth.of with flow function * fix RxSourceOfTruth name to match original class * specify bounds for FactoryFetcher * updates per PR review * update graph per SoT rename * update rxjava3 APIs as well These appeared after i rebased, missed them completely. Also fixed some tests, appearantly IJ parameter name refactor does not always work * supress wrong unnecessary cast warning without this, multicaster cannot resolve to the base StoreResponse type * upgade gradle, try to fix build by disabling caching * split subscribers * resubscribe Co-authored-by: miken <miken@dropbox.com> Co-authored-by: miken <miken@dropbox.com>
2020-06-19 10:00:50 +00:00
fetcher = Fetcher.of { api.fetchSubreddit(it, "10").data.children.map(::toPosts) },
sourceOfTruth = SourceOfTruth.of(
reader = db.postDao()::loadPosts,
writer = db.postDao()::insertPosts,
delete = db.postDao()::clearFeed,
deleteAll = db.postDao()::clearAllFeeds
)
).build()
2019-11-05 02:11:07 +00:00
```
2017-01-04 19:17:53 +00:00
Stores dont care how youre 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). Technically, there is nothing stopping you from implementing an in-memory cache for the "sourceOfTruth" implementation and instead have two levels of in-memory caching--one with inflated and one with deflated models, allowing for sharing of the “sourceOfTruth” cache data between stores.
2017-01-04 19:17:53 +00:00
2019-12-11 01:46:08 +00:00
If using SQLite we recommend working with [Room](https://developer.android.com/topic/libraries/architecture/room) which returns a `Flow` from a query
2019-11-05 02:11:07 +00:00
The above builder is how we recommend working with data on Android. With the above setup you have:
2019-12-23 17:31:37 +00:00
+ Memory caching with TTL & Size policies
2019-11-05 02:11:07 +00:00
+ Disk caching with simple integration with Room
+ In-flight request management
+ Ability to get cached data or bust through your caches (`get()` vs. `fresh()`)
2017-02-10 17:17:28 +00:00
+ Ability to listen for any new emissions from network (stream)
2019-12-23 17:31:37 +00:00
+ Structured Concurrency through APIs build on Coroutines and Kotlin Flow
### Configuring in-memory Cache
You can configure in-memory cache with the `MemoryPolicy`:
```kotlin
StoreBuilder
.from(
Yigit/move fetcher factories to fetcher (#168) (#181) * Move Fetcher factories into companion Fetcher factories were global methods, which made them hard to discover since IDE cannot easily auto-complete. This PR moves them into the companion of Fetcher while also making Fetcher a real interface instead of a typealias. Even though it is a bit more code for the developer, now they can easily discover how to create a Fetcher by typing Fetcher. Fixes: #167 * make rx methods start w/ from too for consistency * Rename fether factories to be more clear, hopefully :/ * remove fetch method, use invoke instead * Make Fetcher.from the one that receives a suspend fun. Create Fetcher.fromFlow for the flowing version. Rename both SourceOfTruth builder methods to . Rely on param names to disambiguate * use .of instead, this seems better to me. We should probably get rid of StoreBuilder.from and make it Store.builder() * fix jvm name for SourceOfTruth.of with flow function * fix RxSourceOfTruth name to match original class * specify bounds for FactoryFetcher * updates per PR review * update graph per SoT rename * update rxjava3 APIs as well These appeared after i rebased, missed them completely. Also fixed some tests, appearantly IJ parameter name refactor does not always work * supress wrong unnecessary cast warning without this, multicaster cannot resolve to the base StoreResponse type * upgade gradle, try to fix build by disabling caching * split subscribers * resubscribe Co-authored-by: miken <miken@dropbox.com> Co-authored-by: miken <miken@dropbox.com>
2020-06-19 10:00:50 +00:00
fetcher = Fetcher.of { api.fetchSubreddit(it, "10").data.children.map(::toPosts) },
sourceOfTruth = SourceOfTruth.of(
reader = db.postDao()::loadPosts,
writer = db.postDao()::insertPosts,
delete = db.postDao()::clearFeed,
deleteAll = db.postDao()::clearAllFeeds
)
).cachePolicy(
MemoryPolicy.builder()
.setMemorySize(10)
.setExpireAfterAccess(10.minutes) // or setExpireAfterWrite(10.minutes)
.build()
).build()
```
* `setMemorySize(maxSize: Long)` sets the maximum number of entries to be kept in the cache before starting to evict the least recently used items.
* `setExpireAfterAccess(expireAfterAccess: Duration)` sets the maximum time an entry can live in the cache since the last access, where "access" means reading the cache, adding a new cache entry, and replacing an existing entry with a new one. This duration is also known as **time-to-idle (TTI)**.
* `setExpireAfterWrite(expireAfterWrite: Duration)` sets the maximum time an entry can live in the cache since the last write, where "write" means adding a new cache entry and replacing an existing entry with a new one. This duration is also known as **time-to-live (TTL)**.
Note that `setExpireAfterAccess` and `setExpireAfterWrite` **cannot** both be set at the same time.
### Clearing store entries
You can delete a specific entry by key from a store, or clear all entries in a store.
#### Store with no sourceOfTruth
```kotlin
val store = StoreBuilder
Yigit/move fetcher factories to fetcher (#168) (#181) * Move Fetcher factories into companion Fetcher factories were global methods, which made them hard to discover since IDE cannot easily auto-complete. This PR moves them into the companion of Fetcher while also making Fetcher a real interface instead of a typealias. Even though it is a bit more code for the developer, now they can easily discover how to create a Fetcher by typing Fetcher. Fixes: #167 * make rx methods start w/ from too for consistency * Rename fether factories to be more clear, hopefully :/ * remove fetch method, use invoke instead * Make Fetcher.from the one that receives a suspend fun. Create Fetcher.fromFlow for the flowing version. Rename both SourceOfTruth builder methods to . Rely on param names to disambiguate * use .of instead, this seems better to me. We should probably get rid of StoreBuilder.from and make it Store.builder() * fix jvm name for SourceOfTruth.of with flow function * fix RxSourceOfTruth name to match original class * specify bounds for FactoryFetcher * updates per PR review * update graph per SoT rename * update rxjava3 APIs as well These appeared after i rebased, missed them completely. Also fixed some tests, appearantly IJ parameter name refactor does not always work * supress wrong unnecessary cast warning without this, multicaster cannot resolve to the base StoreResponse type * upgade gradle, try to fix build by disabling caching * split subscribers * resubscribe Co-authored-by: miken <miken@dropbox.com> Co-authored-by: miken <miken@dropbox.com>
2020-06-19 10:00:50 +00:00
.from(
fetcher = Fetcher.of { key: String ->
api.fetchData(key)
}).build()
```
The following will clear the entry associated with the key from the in-memory cache:
```kotlin
store.clear("10")
```
The following will clear all entries from the in-memory cache:
```kotlin
store.clearAll()
```
#### Store with sourceOfTruth
When store has a sourceOfTruth, you'll need to provide the `delete` and `deleteAll` functions for `clear(key)` and `clearAll()` to work:
```kotlin
StoreBuilder
.from(
Yigit/move fetcher factories to fetcher (#168) (#181) * Move Fetcher factories into companion Fetcher factories were global methods, which made them hard to discover since IDE cannot easily auto-complete. This PR moves them into the companion of Fetcher while also making Fetcher a real interface instead of a typealias. Even though it is a bit more code for the developer, now they can easily discover how to create a Fetcher by typing Fetcher. Fixes: #167 * make rx methods start w/ from too for consistency * Rename fether factories to be more clear, hopefully :/ * remove fetch method, use invoke instead * Make Fetcher.from the one that receives a suspend fun. Create Fetcher.fromFlow for the flowing version. Rename both SourceOfTruth builder methods to . Rely on param names to disambiguate * use .of instead, this seems better to me. We should probably get rid of StoreBuilder.from and make it Store.builder() * fix jvm name for SourceOfTruth.of with flow function * fix RxSourceOfTruth name to match original class * specify bounds for FactoryFetcher * updates per PR review * update graph per SoT rename * update rxjava3 APIs as well These appeared after i rebased, missed them completely. Also fixed some tests, appearantly IJ parameter name refactor does not always work * supress wrong unnecessary cast warning without this, multicaster cannot resolve to the base StoreResponse type * upgade gradle, try to fix build by disabling caching * split subscribers * resubscribe Co-authored-by: miken <miken@dropbox.com> Co-authored-by: miken <miken@dropbox.com>
2020-06-19 10:00:50 +00:00
fetcher = Fetcher.of { api.fetchData(key) },
sourceOfTruth = SourceOfTruth.of(
reader = dao::loadData,
writer = dao::writeData,
delete = dao::clearDataByKey,
deleteAll = dao::clearAllData
)
).build()
```
The following will clear the entry associated with the key from both the in-memory cache and the sourceOfTruth:
```kotlin
store.clear("myKey")
```
The following will clear all entries from both the in-memory cache and the sourceOfTruth:
```kotlin
store.clearAll()
2020-01-29 15:37:14 +00:00
```