Avoid popUpTo and navigateTo same route

pull/1470/head
anhtuannd 1 year ago
parent 940497f176
commit b3f3ebe2f0

@ -33,8 +33,11 @@ import com.google.samples.apps.nowinandroid.core.data.repository.UserNewsResourc
import com.google.samples.apps.nowinandroid.core.data.util.NetworkMonitor
import com.google.samples.apps.nowinandroid.core.data.util.TimeZoneMonitor
import com.google.samples.apps.nowinandroid.core.ui.TrackDisposableJank
import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.BookmarksRoute
import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.navigateToBookmarks
import com.google.samples.apps.nowinandroid.feature.foryou.navigation.ForYouRoute
import com.google.samples.apps.nowinandroid.feature.foryou.navigation.navigateToForYou
import com.google.samples.apps.nowinandroid.feature.interests.navigation.InterestsRoute
import com.google.samples.apps.nowinandroid.feature.interests.navigation.navigateToInterests
import com.google.samples.apps.nowinandroid.feature.search.navigation.navigateToSearch
import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination
@ -142,17 +145,22 @@ class NiaAppState(
fun navigateToTopLevelDestination(topLevelDestination: TopLevelDestination) {
trace("Navigation: ${topLevelDestination.name}") {
val topLevelNavOptions = navOptions {
val startDestination = navController.graph.findStartDestination()
// Avoid popUpTo and navigate to same screen.
val shouldNotSavedAndRestored = isStartDestinationSameWithNextDestination(
startDestination, topLevelDestination
) ?: false
// Pop up to the start destination of the graph to
// avoid building up a large stack of destinations
// on the back stack as users select items
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
saveState = !shouldNotSavedAndRestored
}
// Avoid multiple copies of the same destination when
// reselecting the same item
launchSingleTop = true
launchSingleTop = !shouldNotSavedAndRestored
// Restore state when reselecting a previously selected item
restoreState = true
restoreState = !shouldNotSavedAndRestored
}
when (topLevelDestination) {
@ -163,6 +171,14 @@ class NiaAppState(
}
}
/**
* Check if next destination is same with start destination of current graph.
*/
private fun isStartDestinationSameWithNextDestination(
startDestination: NavDestination,
nextDestination: TopLevelDestination,
): Boolean? = startDestination.hasRoute(nextDestination.route)
fun navigateToSearch() = navController.navigateToSearch()
}

Loading…
Cancel
Save