https://kotlinlang.org logo
a

Alexandru Hadăr

10/12/2022, 7:52 PM
How should we observe a flow to navigate to a different screen, when using @Compose and ViewModel? Suppose we wait for a
logout
call to finish, how should we collect the flow result in a @Composable function? The only way I could think of would be something like this:
Copy code
@Composable
private fun ProfileScreen(
    onUserLoggedOut: () -> Unit,
    viewModel: UserProfileViewModel = viewModel()
) {
    LaunchedEffect(key1 = Unit) {
        viewModel.onUserLoggedOut.collect { userLoginState ->
            when (userLoginState) {
                UserLoginState.LOGGED_IN -> Unit // do nothing
                UserLoginState.LOGGED_OUT -> onUserLoggedOut()
            }
        }
    }
}
However, it seems a bit off. IS there any better solution to this?
k

Kevin Healy

10/12/2022, 8:00 PM
If I was you I'd collect the flow as state and then use its value as the key for your LaunchedEffect
Copy code
val userLoginState by viewModel.onUserLoggedOut.collectAsState()

LaunchedEffect(key1 = userLoginState) {
    when (userLoginState) {
        //do stuff
    }
}
Although I guess by the name that you're really responding to an event (the user did log out) rather than the state (the user is logged out), which doesn't fit as nicely into Compose
a

Alexandru Hadăr

10/12/2022, 8:14 PM
Do you have any idea how I could replace that? How I could better handle events?
k

Kevin Healy

10/12/2022, 8:16 PM
Also this handy set of links (includes the above) https://twitter.com/Tunji_D/status/1579827057596727301
14 Views