这是indexloc提供的服务,不要输入任何密码
Skip to content

[Navigation] Return early from NavigatorProvider#addNavigator if possible #176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ public open class NavigatorProvider {
): Navigator<out NavDestination>? {
require(validateName(name)) { "navigator name cannot be an empty string" }
val previousNavigator = _navigators[name]
if (previousNavigator == navigator) {
return navigator
}
check(previousNavigator?.isAttached != true) {
"Navigator $navigator is replacing an already attached $previousNavigator"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package androidx.navigation

import android.os.Bundle
import androidx.navigation.testing.TestNavigatorState
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import org.junit.Assert.fail
Expand Down Expand Up @@ -100,6 +101,50 @@ class NavigatorProviderTest {
.isEqualTo(navigator)
}

@Test
fun addExistingNavigatorDoesntReplace() {
val navigatorState = TestNavigatorState()
val provider = NavigatorProvider()
val navigator = EmptyNavigator()

provider.addNavigator(navigator)
assertThat(provider.getNavigator<EmptyNavigator>(EmptyNavigator.NAME))
.isEqualTo(navigator)

navigator.onAttach(navigatorState)
assertWithMessage("Navigator should be attached")
.that(provider.getNavigator<EmptyNavigator>(EmptyNavigator.NAME).isAttached)
.isTrue()

// addNavigator should throw when trying to replace an existing, attached navigator, but
// we should have returned before that
try {
provider.addNavigator(navigator)
} catch (navigatorAlreadyAttached: IllegalStateException) {
fail(
"addNavigator with an existing navigator should return early and not " +
"attempt to replace"
)
}
}

@Test
fun addWithSameNameButUnequalNavigatorDoesReplace() {
val provider = NavigatorProvider()
val navigatorA = EmptyNavigator()
val navigatorB = EmptyNavigator()

assertThat(navigatorA).isNotEqualTo(navigatorB)

provider.addNavigator(navigatorA)
assertThat(provider.getNavigator<EmptyNavigator>(EmptyNavigator.NAME))
.isEqualTo(navigatorA)

provider.addNavigator(navigatorB)
assertThat(provider.getNavigator<EmptyNavigator>(EmptyNavigator.NAME))
.isEqualTo(navigatorB)
}

private val provider = NavigatorProvider()

@Test
Expand Down