Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class SampleViewModel : ViewModel() {
val sampleData = UiAsyncLoadLiveData<String> {
value = try {
async(coroutineContext + CommonPool) {
"very long time process!"
}.await()
} catch (e: CancellationException) {
null
}
}
}
class UiAsyncLoadLiveData<T>(
private val onActive: suspend UiAsyncLoadLiveData<T>.() -> Unit
) : MutableLiveData<T>() {
private var job = EMPTY_JOB
override fun onActive() {
if (job.isActive || value != null) {
return
}
job = launch(UI) {
onActive.invoke(this@UiAsyncLoadLiveData)
}
}
override fun onInactive() {
job.cancel()
}
fun retry(resetValue: Boolean = true) {
if (resetValue) {
value = null
}
if (hasActiveObservers()) {
if (job.isActive) {
job.cancel()
}
onActive()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment