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?
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With