Skip to content

Instantly share code, notes, and snippets.

@AchrafAmil
Last active August 5, 2023 06:23
Show Gist options
  • Save AchrafAmil/802ee7df3e34986aa59caa52529a40ae to your computer and use it in GitHub Desktop.
Save AchrafAmil/802ee7df3e34986aa59caa52529a40ae to your computer and use it in GitHub Desktop.
Kotlin coroutine scope associated with an Android View (scope cancelled on view detached and re-initialized in case it's re-attached)
import android.view.View
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
val View.viewCoroutineScope: CoroutineScope
get() {
var viewScope = getTag(R.id.viewCoroutineScope) as CoroutineScope?
if (viewScope == null) {
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewDetachedFromWindow(v: View?) {
setTag(R.id.viewCoroutineScope, null)
scope.cancel()
}
override fun onViewAttachedToWindow(v: View?) {
/* no-op */
}
})
setTag(R.id.viewCoroutineScope, scope)
viewScope = scope
}
return viewScope
}
<!-- res/values/tags.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="viewCoroutineScope" />
</resources>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment