Skip to content

Instantly share code, notes, and snippets.

@afollestad
Created November 30, 2018 22:22
Show Gist options
  • Select an option

  • Save afollestad/177f602e74fdc5db6b9c9a2e3f263a6b to your computer and use it in GitHub Desktop.

Select an option

Save afollestad/177f602e74fdc5db6b9c9a2e3f263a6b to your computer and use it in GitHub Desktop.
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