Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
suspend fun <F : Fragment> FragmentManager.awaitFragmentById(idRes: Int) =
suspendCancellableCoroutine<F> {
val backStackListener = object : FragmentManager.OnBackStackChangedListener {
override fun onBackStackChanged() {
val f = findFragmentById(idRes) as F?
if (f != null) {
removeOnBackStackChangedListener(this)
it.resume(f)
}
}
}
addOnBackStackChangedListener(backStackListener)
it.invokeOnCancellation { removeOnBackStackChangedListener(backStackListener) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment