Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Compose LaunchedEffect with delay stuck in instrumentation tests

I implemented custom simple splash screen with compose navigation. To navigate to main screen after short period of time I used LaunchedEffect with delay inside. It works fine. But in UI test the invocation in LaunchedEffect stuck at delay. Here is example:

@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()
}

The only solution that I came up with is to use ViewModel and use delay in viewModelScope. But by this way I ruined whole idea of using navigation to show splash screen.

like image 885
Denis Elkin Avatar asked Sep 11 '25 03:09

Denis Elkin


1 Answers

I know this is an old question, but I also ran into a similar issue, so here's what I did to get past the delay inside a LaunchedEffect.

You can use composeTestRule.mainClock.advanceTimeBy(200) in your test to get past the delay.

like image 170
kungpaogao Avatar answered Sep 13 '25 17:09

kungpaogao