Archie G. Quiñones
Archie G. Quiñones

Reputation: 13648

What problem does liveData builder function solve?

So there is a new builder function for LiveData which is:

val someLiveData = liveData {
    // do something
}

Can anyone explain exactly what this new builder function solve? How does it solve issues on rotation? How does it relate to webservice calls?

Any inputs would be appreciated. Thanks in advance.

Upvotes: 5

Views: 675

Answers (1)

Enselic
Enselic

Reputation: 4902

Can anyone explain exactly what this new builder function solve?

The current documentation on liveData { } it is pretty good and gives many examples. Here are some benefits you get for free by using it:

  • Automatic support for timeout and canceling through the optional timeoutInMs (which defaults to 5 seconds).
  • No need to explicitly launch a coroutine from an init { } block to initialize a MutableLiveData<T> (this hypothetical coroutine is referred to as C below).
  • No need to worry about what scope to launch C in
  • No need to maintain code to wait with launching C until it is actually needed (i.e. the LiveData has any registered and active observers).
  • No need to write code for relaunching C when the LiveData is re-activated.

How does it solve issues on rotation?

LiveData in itself does not solve any issue with preserving state across e.g. screen rotation. That's what ViewModel is for. Typically you have LiveData properties in your ViewModel. But there is not direct relationship between screen rotation problems and liveData { }

How does it relate to webservice calls?

Since the block you pass to liveData { } is a suspend function, you can use coroutine support in your webservice. For example, Retrofit 2.6.0 and later supports suspend modifiers in its HTTP request function definitions, which makes it very convenient to use in the liveData { } code block.

Upvotes: 2

Related Questions