Skip to content

Instantly share code, notes, and snippets.

@diousk
Created April 8, 2020 13:12
Show Gist options
  • Save diousk/26398021d21be6ccf3758e55caca47de to your computer and use it in GitHub Desktop.
Save diousk/26398021d21be6ccf3758e55caca47de to your computer and use it in GitHub Desktop.
suspend fun View.awaitLayout() = suspendCancellableCoroutine<Unit>{ cont ->
if (isLaidOut) {
// if view is laid out, just resume coroutine
cont.resume(Unit)
return@suspendCancellableCoroutine
}
val listener = object : View.OnLayoutChangeListener {
override fun onLayoutChange(
view: View,
left: Int,
top: Int,
right: Int,
bottom: Int,
oldLeft: Int,
oldTop: Int,
oldRight: Int,
oldBottom: Int
) {
view.removeOnLayoutChangeListener(this)
cont.resume(Unit)
}
}
// remove listener when the job is cancelled
cont.invokeOnCancellation { removeOnLayoutChangeListener(listener) }
addOnLayoutChangeListener(listener)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment