Skip to content

Instantly share code, notes, and snippets.

@hansenji
Created December 9, 2020 23:03
Show Gist options
  • Save hansenji/0172aa2027a8a0837676726c09196cd4 to your computer and use it in GitHub Desktop.
Save hansenji/0172aa2027a8a0837676726c09196cd4 to your computer and use it in GitHub Desktop.
Coroutine Scope for a view.
import android.view.View
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import kotlin.coroutines.CoroutineContext
internal val View.viewScope: ViewCoroutineScope
get() {
val scope = getTag(R.id.coroutineScope) as ViewCoroutineScope?
if (scope != null) {
return scope
}
val newScope = ViewCoroutineScope(this, SupervisorJob() + Dispatchers.Main.immediate)
setTag(R.id.coroutineScope, newScope)
return newScope
}
internal class ViewCoroutineScope(view: View, override val coroutineContext: CoroutineContext) : CoroutineScope {
init {
view.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(v: View?) {
// Do nothing
}
override fun onViewDetachedFromWindow(v: View?) {
coroutineContext.cancelChildren()
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment