Created
June 19, 2017 03:00
-
-
Save STAR-ZERO/3815156b80ad5d2d60122b36129c095b to your computer and use it in GitHub Desktop.
LiveData + Kotlin Coroutine
This file contains hidden or 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
// 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() | |
} | |
} |
This file contains hidden or 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
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