Skip to content

Instantly share code, notes, and snippets.

@STAR-ZERO
Created June 19, 2017 03:00
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save STAR-ZERO/3815156b80ad5d2d60122b36129c095b to your computer and use it in GitHub Desktop.
Save STAR-ZERO/3815156b80ad5d2d60122b36129c095b 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