Created
November 30, 2018 22:22
-
-
Save afollestad/177f602e74fdc5db6b9c9a2e3f263a6b to your computer and use it in GitHub Desktop.
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.Job | |
| import kotlin.coroutines.CoroutineContext | |
| fun View.scopeWhileAttached( | |
| context: CoroutineContext, | |
| exec: CoroutineScope.() -> Unit | |
| ) { | |
| val job = Job(context[Job]) | |
| addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { | |
| override fun onViewAttachedToWindow(v: View) = Unit | |
| override fun onViewDetachedFromWindow(v: View) { | |
| job.cancel() | |
| } | |
| }) | |
| exec(CoroutineScope(context + job)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment