我使用组合导航实现了自定义简单启动画面。为了在短时间内导航到主屏幕,我使用了
LaunchedEffect
和 delay
里面。它工作正常。但是在 UI 测试中,LaunchedEffect
中的调用停留在 delay
。
这是例子:
@Composable
private fun Navigation() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "splash") {
composable("splash") {
SplashScreen {
navController.navigate("main") {
popUpTo("splash") {
inclusive = true
}
}
}
}
composable("main") { MainScreen() }
}
}
@Composable
private fun SplashScreen(
onComplete: () -> Unit,
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
)
val currentOnComplete by rememberUpdatedState(onComplete)
LaunchedEffect(Unit) {
delay(200)
currentOnComplete()
}
}
@Composable
private fun MainScreen() {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize()
.background(Color.White),
) {
Text("Main Screen")
}
}
@Test
fun testMainScreen() {
onView(isRoot()).perform(waitFor(2000))
composeTestRule.onNodeWithText("Main Screen").assertIsDisplayed()
}
我想出的唯一解决方案是使用
ViewModel
并在delay
中使用viewModelScope
。但是通过这种方式,我破坏了使用导航显示启动画面的整个想法。