Skip to content

Instantly share code, notes, and snippets.

@fdoyle
Created April 14, 2023 18:49
Show Gist options
  • Save fdoyle/2f15615d8976651ddbe786c6c2da4315 to your computer and use it in GitHub Desktop.
Save fdoyle/2f15615d8976651ddbe786c6c2da4315 to your computer and use it in GitHub Desktop.
A cool way to do derivedState with LiveData
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)
}
}
}
@ilyaserg
Copy link

ilyaserg commented Apr 17, 2023

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