Search code examples
androidandroid-livedataandroid-architecture-components

What's the best way to update LiveData in Android?


I have the two ways to update a LiveData's value.

Fitst

myLiveData.value = myLiveData.value?.apply {
    arg1 = value1
    arg2 = value2
}

Just update existing value and pass it again.

Second

viewState.value = MyObject(arg1 = value1, arg2 = value2)

Create a new object every time and pass it.

Whisch the way is better in terms of optimisation and code beauty?

P.S. The first term is much more important. Thx in advance.


Solution

  • If you have two values that must be available at the same time, the second approach is the only one that makes sense. With the first approach, the first value will get quickly overwritten by the second. It's entirely possible that an observer could miss the first value. And, an observer that gets attached after the second value is set will only ever see the second value.

    The cost of creating a new object every time is not very big. Don't try to optimize that way - it's simply not relevant.