Skip to content

Instantly share code, notes, and snippets.

@kimji1
Last active July 15, 2022 08:43
Show Gist options
  • Select an option

  • Save kimji1/159b2e393b529ddfa46101e2b30ec30a to your computer and use it in GitHub Desktop.

Select an option

Save kimji1/159b2e393b529ddfa46101e2b30ec30a to your computer and use it in GitHub Desktop.
fun Fragment.findNavControllerSafety(): NavController? {
try {
val fragmentName = this.javaClass.name
val controller = NavHostFragment.findNavController(this)
val isCurrentDestination = when (val currentDestination = controller.currentDestination) {
is DialogFragmentNavigator.Destination -> currentDestination.className == fragmentName
is FragmentNavigator.Destination -> currentDestination.className == fragmentName
else -> false
}
if (!isCurrentDestination) {
Timber.i("Navigation currentDestination not match: ${controller.currentDestination?.displayName}, $fragmentName")
return null
}
return controller
} catch (e: Exception) {
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment