LiveDataBuilder in Kotlin Android

iamVariable
2 min readOct 21, 2022

In our previous article we saw, how viewModelScope help us to remove boilerplate codes. If you haven’t read it, I share you the link below go ahead and give a try for better understanding.

https://i-amvariable.medium.com/viewmodelscope-in-android-93e37a98acae

In short, to remove more boilerplate codes we used viewModelScope. Here is LiveDataBuilder introduced with androidx.lifecycle:lifecycle-livedata-ktx

Live Data Builder fills in the gap between Live Data and Coroutines.

So how does liveDataBuilder works?

  • The coroutine only starts when the Live Data is active, meaning it should have at least one active observer.
  • If the Live Data becomes inactive while the coroutine is executing, it will wait until [timeoutInMs] and if there’s still no longer observing, it will get cancelled.
  • If the live data becomes active again after cancellation, it will execute again. However if it was completed or even threw an exception then it would not be restarted.
  • It runs in main thread by default but thread can be switched by using it like liveData(Dispatchers.IO) {..}
  • emit() can be called from within any thread.

The below is the existing code which is using viewModelScope

private val userMutableLiveData = MutableLiveData<List<User>>()
val userLiveDataList: LiveData<List<User>> get() = userMutableLiveData

fun getUserData() {
viewModelScope.launch {
var result: List<User>? = null
withContext(Dispatchers.IO) {
result = repository.getUsers()
userMutableLiveData.postValue(result!!)
}
}
}

Here is the example with LiveDataBuilder.

private val repository = UserRepository()

val userLiveDataList = liveData(Dispatchers.IO) {
val user = repository.getUsers()
emit(user)
}

So, you clearly understand that again we optimised n number codes.

However, you should still can use viewModelScope for coroutines that are independent of the View. A use case scenario would be when you’re using a shared viewModel between fragments and you want coroutines to still run even when a certain observer from the view is removed or the live data isn’t active anymore..

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 HTTPS request function definitions, which makes it very convenient to use in the liveData { } code block.

Happy Coding:)

--

--

iamVariable

Experienced Mobile Application developer and in full software development lifecycle, including analysis, design, development, deployment.