Created
April 8, 2020 13:12
-
-
Save diousk/26398021d21be6ccf3758e55caca47de to your computer and use it in GitHub Desktop.
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
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