So I've tried using MediatorLiveData for the rather simple use-case of converting an ISO country code (e.g. "US") to a country calling code (e.g. "+1") through the use of libphonenumber. The resulting screen works fine, but seems to fail JUnit tests, even when InstantTaskExecutorRule is used.
Example minimal unit test (in Kotlin) that I believe should pass, but fails instead:
import android.arch.core.executor.testing.InstantTaskExecutorRule
import android.arch.lifecycle.MediatorLiveData
import android.arch.lifecycle.MutableLiveData
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
class MediatorLiveData_metaTest {
@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
@Test
fun mediatorLiveData_metaTest() {
val sourceInt = MutableLiveData<Int>()
val mediatedStr = MediatorLiveData<String>()
mediatedStr.addSource(sourceInt) {
mediatedStr.value = it.toString()
}
sourceInt.value = 123
assertEquals("123", mediatedStr.value) // says mediatedStr.value is null
}
}
Thanks to Reddit user matejdro; the answer was that like Schrödinger's proverbial cat, MediatorLiveData won't update itself unless observed, so I'd need a mediatedStr.observeForever{}
to force it to update itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With