Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save suclike/29d9b1094f1a33e867e8b2f0c052524e to your computer and use it in GitHub Desktop.

Select an option

Save suclike/29d9b1094f1a33e867e8b2f0c052524e to your computer and use it in GitHub Desktop.
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([email protected]()) }
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