Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to find the liveData building block?

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?

like image 699
Ninja420 Avatar asked May 23 '19 19:05

Ninja420


People also ask

What is LiveData builder?

The liveData building block serves as a structured concurrency primitive between coroutines and LiveData . The code block starts executing when LiveData becomes active and is automatically canceled after a configurable timeout when the LiveData becomes inactive.

What is MutableLiveData in Android Kotlin?

MutableLiveData is just a class that extends the LiveData type class. MutableLiveData is commonly used since it provides the postValue() , setValue() methods publicly, something that LiveData class doesn't provide.

What is LiveData in Mvvm Android?

LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.


1 Answers

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)
like image 50
gMale Avatar answered Sep 24 '22 16:09

gMale