Created
December 9, 2020 23:03
-
-
Save hansenji/0172aa2027a8a0837676726c09196cd4 to your computer and use it in GitHub Desktop.
Coroutine Scope for a view.
This file contains 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.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