android 在rememberUpdatedState()中记住lambda函数的用法

bgibtngc  于 2024-01-04  发布在  Android
关注(0)|答案(1)|浏览(238)

我在谷歌的撰写文档(链接)中看到,
有一个LoginScreenCompose函数,基于一个动作(例如,这里,成功登录),我们希望然后使用lambda函数从LoginScreen的输入导航到HomeScreen
在Google文档的例子中,他们记住了LoginScreen rememberUpdatedState()输入的lambda函数,当成功登录时,rememberUpdatedState()的值用于导航。

  1. @Composable
  2. fun LoginScreen(
  3. onUserLogIn: () -> Unit, // Caller navigates to the right screen
  4. viewModel: LoginViewModel = viewModel()
  5. ) {
  6. Button(
  7. onClick = {
  8. // ViewModel validation is triggered
  9. viewModel.login()
  10. }
  11. ) {
  12. Text("Log in")
  13. }
  14. // Rest of the UI
  15. val lifecycle = LocalLifecycleOwner.current.lifecycle
  16. val currentOnUserLogIn by rememberUpdatedState(onUserLogIn)
  17. LaunchedEffect(viewModel, lifecycle) {
  18. // Whenever the uiState changes, check if the user is logged in and
  19. // call the `onUserLogin` event when `lifecycle` is at least STARTED
  20. snapshotFlow { viewModel.uiState }
  21. .filter { it.isUserLoggedIn }
  22. .flowWithLifecycle(lifecycle)
  23. .collect {
  24. currentOnUserLogIn()
  25. }
  26. }
  27. }

字符串
我知道rememberUpdatedState()的用法,用于记住一个值并获取最新的
但是这个结构的用法是从一个rememberedUpdateState非直接调用lambda函数(onUserLogIn()),
为什么不直接调用onUserLogIn lambda函数呢?

5kgi1eie

5kgi1eie1#

这就是rememberUpdatedState的作用--将更新的状态传递到LaunchedEffect中。如果直接调用onUserLogIn,它将使用LaunchedEffect启动时的初始值。

相关问题