Skip to content

Instantly share code, notes, and snippets.

@kaneoriley
Created May 5, 2020 23:21
Show Gist options
  • Save kaneoriley/b43da63ee17bd266d77228f46ce2d4c7 to your computer and use it in GitHub Desktop.
Save kaneoriley/b43da63ee17bd266d77228f46ce2d4c7 to your computer and use it in GitHub Desktop.
Safe navigation
/** Workaround for 'unknown to this navigation controller' error */
fun Fragment.isCurrentDestination(): Boolean {
val navController = findNavController()
val currentDestinationId = navController.currentDestination?.id
val fragmentDestinationId = view?.getTag(R.id.tag_navigation_destination_id) ?: currentDestinationId
return if (currentDestinationId == fragmentDestinationId) {
view?.setTag(R.id.tag_navigation_destination_id, fragmentDestinationId)
true
} else {
log.error { "May not navigate: current destination is not the current fragment." }
false
}
}
fun Fragment.safeNavigate(action: NavController.() -> Unit) {
if (isCurrentDestination()) {
findNavController().apply { action.invoke(this) }
}
}
...
// In the fragment:
safeNavigate {
// 'this' is a NavController that's able to navigate without error
navigate(/** whatever overload you need */)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment