Last active
August 5, 2023 06:23
-
-
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)
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment