How do you guys handle nullable states. Doesn't st...
# compose
s
How do you guys handle nullable states. Doesn't stuff like
Text(user?.name ?: "")
make the code ugly?
g
In which cases
user
can be null?
s
Like while it's being fetched:
val user by viewModel.getUser(userId).collectAsState(initial = null)
I thought of having a
User()
with empty strings as default values but not sure if that's the best way
g
I write something like this
Copy code
if (user == null){
Loading()
} else {
User(user)
}
s
I see but in my case it's a screen where practically user will never be null and there's no Loading state for the screen
g
Can you explain why
getUser
returns
Flow
?
s
It maps a
Flow<List<User>>
to a
Flow<User>
The
Flow<List<User>>
fetches users from a network. In the home screen I'm displaying that
List<User>
and when a
User
item is clicked, I'm navigating to another screen and passing that
User
's id. Then I'm loading that user by simply mapping the user list flow.
The empty User way seems good for my case:
val user: User by viewModel.getUser(userId).collectAsState(initial = emptyUser())
g
Hm I have the similar case. I have `List<userID`> displayed and after clicking I load user by his ID and open UserScreen.
Copy code
onClick = {
scope.launch {
val user = viewModel.loadUserById(ID)
openUserScreen(user)
}
}
s
Except that you have a Loading state. I sometimes do
Copy code
user?.let { user ->
    ...
    Text(user.name)
}
but I'm trynna save some indentation here.
g
I have no loading state in this case
Because I load user from database
s
Ah okay I get it you're waiting for the user to load before opening the screen
👌 1
g
How about
Text(user?.name.orEmpty())
?
s
There's a lot of user stuff to be displayed so it gets ugly quickly:
Copy code
Text(user?.name.orEmpty())
CoilImage(user?.picture?.large.orEmpty())
// and a lot of other composables
j
Maybe you could specify in the composable that user must not be null and check from the caller if the user is null don't show it or show an empty one.
Copy code
@Composable
fun UserScreen(user: User?) {
  user?.let { UserInfo(it) } ?: EmptyComponent()
}

@Composable
fun UserInfo(user: User) {
  Text(user.name.orEmpty())
  CoilImage(user.picture?.large.orEmpty())
  // and a lot of other composables
}
☝️ 1
s
Yeah that looks good too, thanks!