Last active
May 23, 2018 10:21
-
-
Save chibatching/42481bc79f3668d1207e1bc37acdcc18 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SampleViewModel : ViewModel() { | |
val sampleData = UiAsyncLoadLiveData<String> { | |
value = try { | |
async(coroutineContext + CommonPool) { | |
"very long time process!" | |
}.await() | |
} catch (e: CancellationException) { | |
null | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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