https://kotlinlang.org logo
#compose
Title
# compose
o

oday

08/21/2022, 1:58 PM
so if I have Activity A that setContent to Authentication composable Authentication has a viewmodel, inside the viewmodel I’m calling signIn and it’s a long-running process and then a result appears, I hate uiState.value to be the user that I just fetched and so it’s a successful login where do I listen to this state so that I could setContent to a new Composable “Home”? and if I do that where will Home be loaded, in MainActivity as well yea?
looks so wrong
Copy code
class AuthenticationActivity : ComponentActivity() {

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

        val viewModel: AuthenticationViewModel by viewModels()

        lifecycleScope.launch {
            viewModel.uiState.collect { uiState ->
                if (uiState.authenticated) {
                    setContent {
                        Home()
                    }
                }
            }
        }

        setContent {
            MaterialTheme {
                AuthenticationContent(
                    state = viewModel.uiState.collectAsState().value,
                    handleEvent = viewModel::handleEvent
                )
            }
        }
    }
}
Essentially. the result of your auth will be some sort of state. you listen to that state and you can do a LaucnhedEffect on that to navigate you. Or you can do something as simple as using that state as a conditional. i.e.
Copy code
@Composable
fun MyApp(){
if (vm.state.loggedIn){
HomeScreen()
} else {
LoginScreen()
}
}
this twitch stream goes over the above architecture document with @Manuel Vivo and I found it to be helpful to have things click around having your state be updated, and then reacting to that state.

https://www.youtube.com/watch?v=CQzuFZjiUMs

o

oday

08/22/2022, 3:24 PM
thank you for the resources, but my question is still about where would the listening to this state happen, if I were inside a composable
suppose I’m here, this is the composable that I replaced for an Activity so I could make it simpler Suppose i’m here and inside the viewModel there’s an authenticate method and it’s triggered from the UI inside AuthenticationContent, and it correctly sets the state of this composable to user logged in true, where would I listen to that outside from the composable, like after I set the theme….before….inside ….where
Copy code
@Composable
fun Authentication() {
    val viewModel: AuthenticationViewModel = viewModel()

    MaterialTheme {
        AuthenticationContent(
            state = viewModel.uiState.collectAsState().value,
            handleEvent = viewModel::handleEvent
        )
    }
}
2 Views