Skip to content

Instantly share code, notes, and snippets.

@kaneoriley
Created May 5, 2020 23:21
Show Gist options
  • Select an option

  • Save kaneoriley/b43da63ee17bd266d77228f46ce2d4c7 to your computer and use it in GitHub Desktop.

Select an option

Save kaneoriley/b43da63ee17bd266d77228f46ce2d4c7 to your computer and use it in GitHub Desktop.

Revisions

  1. kaneoriley created this gist May 5, 2020.
    30 changes: 30 additions & 0 deletions Fragment.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@

    /** 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 */)
    }