5

https://developer.android.com/topic/libraries/architecture/coroutines

Android coroutines plus liveData documentation states that we can use the liveData builder function in case we want to want to perform async operations inside the live data function

val user: LiveData<User> = liveData {
    val data = database.loadUser() // loadUser is a suspend function.
    emit(data)
}
val user: LiveData<Result> = liveData {
    emit(Result.loading())
    try {
        emit(Result.success(fetchUser())
    } catch(ioException: Exception) {
        emit(Result.error(ioException))
    }
}

I tried installing the lifecycle-viewmodel-ktx library but couldn't find this block.

Where is it located?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ninja420
  • 3,542
  • 3
  • 22
  • 34

2 Answers2

9

Try:

implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01'

The function lives here: https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/lifecycle/livedata/ktx/src/main/java/androidx/lifecycle/CoroutineLiveData.kt

And is (currently) defined as:

@UseExperimental(ExperimentalTypeInference::class)
fun <T> liveData(
    context: CoroutineContext = EmptyCoroutineContext,
    timeoutInMs: Long = DEFAULT_TIMEOUT,
    @BuilderInference block: suspend LiveDataScope<T>.() -> Unit
): LiveData<T> = CoroutineLiveData(context, timeoutInMs, block)
gMale
  • 17,147
  • 17
  • 91
  • 116
-1

I also had this problem, I would recommend just adding the dependencies they suggested here.

The issue is Google's Android docs on coroutines were not explicit in mentioning that these ktx extensions specifically (as you would see in the link) are very important to be able to get the liveData builder that supplies the LiveDataScope.

Don't make the mistake of thinking that you can just use lower versions i.e 2.1.0, just use it as explicitly specified in the doc i.e. the alpha/RC versions as in 2.2.0-alpha01.

Shayne3000
  • 607
  • 8
  • 5