Created
April 14, 2023 18:49
-
-
Save fdoyle/2f15615d8976651ddbe786c6c2da4315 to your computer and use it in GitHub Desktop.
A cool way to do derivedState with LiveData
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
import androidx.arch.core.executor.testing.InstantTaskExecutorRule | |
import androidx.lifecycle.LiveData | |
import androidx.lifecycle.MutableLiveData | |
import androidx.lifecycle.Observer | |
import org.junit.Assert.assertEquals | |
import org.junit.Rule | |
import org.junit.Test | |
//pattern inspired by https://github.com/ensody/ReactiveState-Kotlin, no code was copied. | |
class DeriveLiveDataTest { | |
@get:Rule | |
val rule = InstantTaskExecutorRule() | |
@Test | |
fun `test that derivedData works`() { | |
val x = MutableLiveData(0) | |
val y = MutableLiveData(0) | |
val list = mutableListOf<Int>() | |
val derived = derive { | |
val x = get(x) ?: 0 | |
val y = get(y) ?: 0 | |
x + y | |
} | |
derived.observeForever { | |
list.add(it) | |
} | |
x.value = 30 | |
assertEquals(30, derived.value) | |
x.value = 20 | |
assertEquals(20, derived.value) | |
x.value = 10 | |
assertEquals(10, derived.value) | |
y.value = 10 | |
assertEquals(20, derived.value) | |
x.value = 10 | |
assertEquals(20, derived.value) | |
assertEquals(listOf(0, 30, 20, 10, 20), list) | |
} | |
} | |
fun <T> derive(block: DeriveScope<T>.() -> T): LiveData<T> { | |
val ret = MutableLiveData<T>() | |
fun update(deriveScope: DeriveScope<T>) { | |
val result = deriveScope.block() | |
println(result) | |
ret.value = result | |
} | |
val d = DeriveScope { deriveScope -> | |
update(deriveScope) | |
} | |
update(d) | |
return ret | |
} | |
class DeriveScope<T>(val onDataChanged: (DeriveScope<T>) -> Unit) { | |
val liveDataToObserver = mutableMapOf<LiveData<in Nothing>, Observer<Any?>>() | |
fun <A : Any> get(data: LiveData<A>): A? { | |
val o = SkipFirstObserver<Any?> {//subscribing to a LiveData always emits immediately, even though nothing's changed. we don't want to listen to that | |
onChanged() | |
} | |
data.observeForever(o) | |
liveDataToObserver[data] = o | |
return data.value | |
} | |
fun onChanged() { | |
liveDataToObserver.forEach { (data, observer) -> | |
data.removeObserver(observer) | |
} | |
liveDataToObserver.clear() | |
onDataChanged(this) | |
} | |
} | |
class SkipFirstObserver<T>(val block: (T) -> Unit) : Observer<T>{ | |
var first = true | |
var currentValue: T? = null | |
override fun onChanged(newValue: T) { | |
if(first) { | |
first = false | |
currentValue = newValue | |
return | |
} else if (currentValue == newValue) { | |
return | |
} else{ | |
println("emitting $newValue") | |
currentValue = newValue | |
block(newValue) | |
} | |
} | |
} |
Some LiveData does nothing without any Observer. Because of it, we need to add liveData.observeForever(errorsObservable) for tests in the testSetup() function
MediatorLiveData with the same logic
class CombinedLiveData<R>(vararg liveDatas: LiveData<*>,
private val combine: (datas: List<Any?>) -> R) : MediatorLiveData<R>() {
private val datas: MutableList<Any?> = MutableList(liveDatas.size) { null }
init {
for(i in liveDatas.indices){
super.addSource(liveDatas[i]) {
datas[i] = it
value = combine(datas)
}
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I first saw this pattern, I wondered how it handled the case where you have a get() in an if statement, where it may or may not be called. Well, if you didn't call get() on a livedata, then that livedata didn't contribute to the final emitted result, which means changes to it won't cause changes to that emitted result. Some other state has to change before that state can become relevant. If that does happen, get() will be called, and it'll start listening again.