Skip to content

Instantly share code, notes, and snippets.

@diefferson
Forked from STAR-ZERO/AsyncLiveData.kt
Created October 12, 2018 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diefferson/5956fa03e4a21fd621e4d6d2bfac6713 to your computer and use it in GitHub Desktop.
Save diefferson/5956fa03e4a21fd621e4d6d2bfac6713 to your computer and use it in GitHub Desktop.
LiveData + Kotlin Coroutine
// compile "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.16"
// compile "android.arch.lifecycle:runtime:1.0.0-alpha3"
// compile "android.arch.lifecycle:extensions:1.0.0-alpha3"
// kapt "android.arch.lifecycle:compiler:1.0.0-alpha3"
class AsyncLiveData<T> private constructor(private val exec: suspend () -> T) : LiveData<T>() {
private var observer: Observer<T>? = null
private var job: Job? = null
companion object {
fun <T> create(exec: suspend () -> T): AsyncLiveData<T> {
return AsyncLiveData(exec)
}
}
override fun observe(owner: LifecycleOwner?, observer: Observer<T>?) {
super.observe(owner, observer)
this.observer = observer
}
override fun onActive() {
super.onActive()
job = launch(UI) {
val result = async(context + CommonPool) {
exec()
}.await()
value = result
removeObserver(observer)
}
}
override fun onInactive() {
super.onInactive()
job?.cancel()
}
}
AsyncLiveData.create {
delay(3000)
1 + 2
}.observe(owner, Observer {
Log.d("AsyncLiveData", "$it")
})
// log
// D/AsyncLiveData: 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment