0

在将其包裹在NavHost.

原始工作解决方案:
此 JcScreen 用于用户登录
活动ActAuth

@AndroidEntryPoint
class ActAuth : AppCompatActivity() {
    private val viewModel: ViewModelAuth by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            ThemeBasicHRLQ {
                ScreenSignInWithInputValidationDebounce()
            }
        }

        // to collect the state `stateSignIn`,
        // and it works fine
        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.stateAuth.collect { state ->
                    ...
                }
            }
        }
    }
}

JCScreen 的摘要ScreenSignInWithInputValidationDebounce()

@OptIn(ExperimentalComposeUiApi::class, kInternalCoroutinesApi::class)
@Composable
fun ScreenSignInWithInputValidationDebounce(
    viewModel: ViewModelAuth = hiltViewModel()
){
    ....
    val stateSignIn by viewModel.stateAuth.collectAsState()
    ...
}

在我整合高度相似的 JCScreen 以供用户注册之前,一切正常。

@AndroidEntryPoint
class ActAuth : AppCompatActivity() {
    private val viewModel: ViewModelAuth by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            ThemeBasicHRLQ {
                // the new JCScreen
                ScreenAuth()
            }
        }

        // to collect the state `stateSignIn`
        // but, with the new JCScreen, it does not work any more
        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.stateAuth.collect { state ->
                    ...
                }
            }
        }
    }
}
@Composable
fun ScreenAuth() {
    val navController = rememberNavController()
    NavHostAuth(navController = navController)
}
@Composable
fun NavHostAuth(
    navController: NavHostController,
) {
    NavHost(
        navController = navController,
        startDestination = NavRoutesAuth.SignIn.route
    ) {
        // I am still in this same JCScreen,
        // without using the `navController`
        composable(NavRoutesAuth.SignIn.route) {
            ScreenSignInWithInputValidationDebounce(navController)
        }

        composable(NavRoutesAuth.SignUp.route) {
            ScreenSignUpWithInputValidationDebounce(navController)
        }
        
    }
}

enum class NavRoutesAuth(val route: String) {
    SignIn("auth/signin"),
    SignUp("auth/signup"),
}

在我看来,一旦包装成 a NavHost,状态管理就不同了。
这可能是一个类似的问题,但是,我仍然无法解决我上面的问题。

4

0 回答 0