Moritz Post
01/11/2023, 11:25 AMby
delegate, how do you deal with the case that the value is null? An if
check is an option but the value can not be smart-cast. What are you doing in that case? Example:
val user by viewModel.user.collectAsState(null)
if (user != null) {
// user? can not be cast to user?
// Message is "Smart cast to 'User' is impossible, because 'user' is a property that has open or custom getter."
}
For one state object you could also use let
but that is very cumbersome when multiple values should be consumed. Using !!
is also not so nice. Any tips?Csaba Szugyiczki
01/11/2023, 12:25 PM@Composable
fun Screen() {
val user by viewModel.user.collectAsState(null)
ScreenContent(user)
}
}
@Composable
private fun ScreenContent(user: User?) {
if (user != null) {
// user here should be non-null
}
}
Moritz Post
01/11/2023, 12:51 PMMoritz Post
01/11/2023, 12:53 PMval user = viewModel.user.collectAsState(null).value
Thereby you create the intermediate variable under the hood which can be smart-cast as expected.mgrazianodecastro
01/11/2023, 4:38 PMgoku
06/22/2023, 5:13 AM@Composable
fun <T> StateFlow<T>.collectAsStateValue(
): T = collectAsState().value
val user = viewModel.user.collectAsStateValue()
Moritz Post
06/22/2023, 12:45 PMcollectValue()
as it is not tied to a state anymore.