Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kotlin Coroutine Android Loader
internal class CoroutineLifecycleListener(private val deferred: Deferred<*>) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun cancelCoroutine() {
deferred.cancel()
}
}
internal var POOL = newFixedThreadPoolContext(2, "loader")
fun <T> LifecycleOwner.load(loader: () -> T): Deferred<T> {
val deferred = async(context = POOL, start = CoroutineStart.LAZY) { loader() }
val coroutineLifecycleListener = CoroutineLifecycleListener(deferred)
lifecycle.addObserver(coroutineLifecycleListener)
return deferred
}
infix fun <T> Deferred<T>.then(block: (T) -> Unit) = async(context = UI) { block(this@then.await()) }
class MyActivity : AppCompatActivity() {
lateinit var text: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
load {
"This is an expensive loading..."
} then {
text = it
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment