Created
August 30, 2020 05:24
-
-
Save quwac/6dd0a749ee2cb7f83d63a0f0d32173cb to your computer and use it in GitHub Desktop.
CachedLiveData with SavedStateHandle extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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