version 1.2 Note, this is a Fork from Mastercard's Repo
LiveCache is a pure Kotlin Android and extensible library that make it easier to define caching policies for the data you would like to fetch from the network (from the application data layer) and provide reactive callbacks to handle async data loading considering android components lifecycle.
- Lifecycle-aware: benefits from LiveData for async events
- Async data loading from network or cache
- Keep fetching, parsing, caching logic in one place
- Preload from cache during network calls
- Simplifies to declare caching strategies
- Repository as single source of truth
- No manual lifecycle managment: no need to register/unregister or subscribe/unsubscribe
- Use Room or whatever persistence library you prefer
Fetch a repository resource using RepoRequest
and react on callback events, notifying the UI:
fun getUser(id: Long) {
RepoRequest(lifecycle) { repo.getUser(id) }
.onLoading { /* on loading event */ }
.onPreload { /* on preload event */ }
.onSuccess { /* on success event*/ }
.onError { /* on error */ }
.execute()
Fetch a resource from the network or from the cache, declaring your cache policy and map a server response into a model object.
fun getUser(id: Long): LiveData<Resource<User>> =
LiveResource.fetch<UserResponse, User>(appExecutors,
isStorable = true,
preload = true) { remote.getUser(id) /*remote call*/ }
.mapper { /* map response */ }
.onResult { /* to execute after mapping */ }
/* Set caching policy */
.setCachePolicy(CachePolicy<User>()
/* define here, is cache valid ? */
.isValid { /* is cache valid ? */ }
.load { /* load from cache */ }
.save { /* save into cache */ })
/* return resource as LiveData */
.asLiveData()
In your build.gradle, add:
implementation 'com.mastercard.labs.android:livecache:$live_cache_version'
Android >= 4.0.1 (API 14).
Copyright 2018 MasterCard International
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.