Skip to content

Instantly share code, notes, and snippets.

@chibatching
Last active May 23, 2018 10:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chibatching/42481bc79f3668d1207e1bc37acdcc18 to your computer and use it in GitHub Desktop.
Save chibatching/42481bc79f3668d1207e1bc37acdcc18 to your computer and use it in GitHub Desktop.
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