Skip to content

Instantly share code, notes, and snippets.

@quwac
Created August 30, 2020 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quwac/6dd0a749ee2cb7f83d63a0f0d32173cb to your computer and use it in GitHub Desktop.
Save quwac/6dd0a749ee2cb7f83d63a0f0d32173cb to your computer and use it in GitHub Desktop.
CachedLiveData with SavedStateHandle extension
//
// Title: CachedLiveData
// Author: quwac (https://github.com/quwac)
// License: CC0 (https://creativecommons.org/publicdomain/zero/1.0/deed.en)
//
package io.github.quwac.cachedlivedata
import androidx.lifecycle.*
fun <T : Any> SavedStateHandle.getCachedLiveData(
key: String,
source: LiveData<T>,
initialValue: T
): LiveData<T> {
val cache = getLiveData(key, initialValue)
return CachedLiveData(source, cache)
}
fun <T : Any> SavedStateHandle.getCachedLiveData(key: String, source: LiveData<T>): LiveData<T> {
val cache = getLiveData<T>(key)
return CachedLiveData(source, cache)
}
private class CachedLiveData<T>(
source: LiveData<T>,
private val cache: MutableLiveData<T>
) : MediatorLiveData<T>() {
private val cacheObserver = Observer<T> {
// nop
}
private var isCacheInSource = true
private var isCacheObserved = false
init {
addSource(source) {
if (isCacheInSource) {
removeSource(cache)
isCacheInSource = false
if (hasActiveObservers()) {
setCacheObserver()
}
}
value = it
cache.value = it
}
addSource(cache) {
value = it
}
}
override fun onActive() {
super.onActive()
setCacheObserver()
}
override fun onInactive() {
super.onInactive()
unsetCacheObserver()
}
private fun setCacheObserver() {
if (!isCacheInSource && !isCacheObserved) {
cache.observeForever(cacheObserver)
isCacheObserved = true
}
}
private fun unsetCacheObserver() {
if (!isCacheInSource && isCacheObserved) {
cache.removeObserver(cacheObserver)
isCacheObserved = false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment