Elias
06/03/2020, 7:53 AMprivate val _foo: MutableLiveData<List<Foo>> = MutableLiveData()
private val _bar: MutableLiveData<List<Bar>> = MutableLiveData()
val fooBar: LiveData<List<FooBar>> = MediatorLiveData<List<FooBar>>.apply {
addSouce(_foo) { this.value = makeFooBarList() }
addSouce(_bar) { this.value = makeFooBarList() }
}
init {
loadFoo()
loadBar()
}
We have been struggling with the viewModel being updated twice or more, which sometimes messes with tests, and can make the views take longer than necessary to load.
Any tips and tricks are appreciated!Vipulyaara
06/03/2020, 11:31 AMfooBar
is expected to have 2 updates; one for foo
and one for bar
. If you only want one update when both foo and bar have some values, write your custom logic inside addSource.
e.g.
addSource(foo) {
// only update if bar exists
if (bar.isNotEmpty()) updateFooBar(foo, bar)
}
// same goes for addSource(bar)
Elias
06/03/2020, 11:36 AMVipulyaara
06/03/2020, 11:38 AMElias
06/03/2020, 11:39 AM