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

Se7eN

10/31/2020, 10:55 AM
How do you guys handle nullable states. Doesn't stuff like
Text(user?.name ?: "")
make the code ugly?
g

Grigorii Yurkov

10/31/2020, 10:58 AM
In which cases
user
can be null?
s

Se7eN

10/31/2020, 10:59 AM
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

Grigorii Yurkov

10/31/2020, 11:00 AM
I write something like this
Copy code
if (user == null){
Loading()
} else {
User(user)
}
s

Se7eN

10/31/2020, 11:02 AM
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

Grigorii Yurkov

10/31/2020, 11:07 AM
Can you explain why
getUser
returns
Flow
?
s

Se7eN

10/31/2020, 11:07 AM
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

Grigorii Yurkov

10/31/2020, 11:24 AM
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

Se7eN

10/31/2020, 11:27 AM
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

Grigorii Yurkov

10/31/2020, 11:30 AM
I have no loading state in this case
Because I load user from database
s

Se7eN

10/31/2020, 11:31 AM
Ah okay I get it you're waiting for the user to load before opening the screen
👌 1
g

Giorgos Neokleous

10/31/2020, 11:36 AM
How about
Text(user?.name.orEmpty())
?
s

Se7eN

10/31/2020, 11:38 AM
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

Jeisson Sáchica

10/31/2020, 3:56 PM
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

Se7eN

10/31/2020, 6:10 PM
Yeah that looks good too, thanks!
2 Views