https://kotlinlang.org logo
#android
Title
# android
e

Elias

06/03/2020, 7:53 AM
Hello, was hoping for some input in to an issue we're having. When using mediator live data, how does one prevent it from updating the dataset twice (or more) on init. EDIT: To clarify, after the viewModel is initialised, we are getting expected behaviouor. See example:
Copy code
private 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!
v

Vipulyaara

06/03/2020, 11:31 AM
fooBar
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.
Copy code
addSource(foo) {
// only update if bar exists
if (bar.isNotEmpty()) updateFooBar(foo, bar)
}
// same goes for addSource(bar)
e

Elias

06/03/2020, 11:36 AM
Well, not quite, while i expect it to later on, i still want the initial update to be only one. So that if either foo or bar is updates when the view is alive it should work as expected.
And it is not a given that foo or bar contains something.
E.g. they are not mutually inclusive.
v

Vipulyaara

06/03/2020, 11:38 AM
So you correctly expect 2 updates on fooBar when foo and bar have some updates?
e

Elias

06/03/2020, 11:39 AM
Yes, it is just when initializing the viewModel that i want one update. After initialization it should behave as it does.