Jetpack Compose NavHost 重组可多次组合

Jetpack Compose NavHost recomposition composable multiple times

我发现在从 Navhost compose 导航期间,可组合屏幕会多次重新组合 以下示例显示了我如何将导航与日志集成,以确定函数被调用了多少次,

internal sealed class Screen(val route: String) {
  object Splash : Screen("splash")
  object Login : Screen("login")
  object Credentials : Screen("credentials/{type}") {
    fun createRoute(type: String) = "credentials/$type"
  }
}

@Composable
fun HostNavGraph(
  modifier: Modifier = Modifier,
  startDestination: String = Splash.route,
) {
  val navController = rememberNavController()
  val vm: CredentialsViewModel = getViewModel()
  NavHost(navController = navController, startDestination = startDestination, modifier = modifier) {
    composable(route = Splash.route) {
      Log.e("composable", " Splash")
      SplashScreen(openLogin = {
        navController.navigate(Login.route)
      }, openRegistration = { type ->
        navController.navigate(Credentials.createRoute(type))
      })
    }
    composable(route = Login.route) {
      Log.e("composable", " Login")
      val context = LocalContext.current
      LoginScreen(openRegistration = { type ->
        navController.navigate(Credentials.createRoute(type))
        {
          popUpTo(Splash.route) { inclusive = false }
        }

      }, openWebView = {
        openWebView(context, it)
      })
    }
    //..
  }
}

在 运行 代码之后,这是打开 Splash 一次然后打开 LoginScreen 一次后导航的行为方式

15:05:14 E/composable:  Splash 
15:05:14 E/composable:  Splash 
15:05:25 E/composable:  Splash 
15:05:25 E/composable:  Login  
15:05:26 E/composable:  Splash 
15:05:26 E/composable:  Login  
15:05:26 E/composable:  Login  

我还尝试了一些 Google 导航组合示例,它的行为方式相同,所以这是预期的行为吗?还是错误
navigation_version = '2.4.0-alpha08'

我不确定,但我认为 NavHost 有一个内置动画,只要有转换。并且对于动画,重组可以像每一帧一样频繁地发生。

A composable function might be run quite frequently, as often as every frame of an animation.

**Android compose

这是 Android Compose 工作方式的一般性质。可组合项会在发现必要时自行重组。阅读文档了解更多详情。