https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Colton Idle

07/24/2022, 9:38 PM
I have found myself writing some snippets similar to this. Is there a better way to do it?
Copy code
fun updateUser(username: String? = null, email: String? = null, token: String? = null) {
  if (username != null) {
    _appUser.value = _appUser.value?.copy(username = username)
  }
  if (email != null) {
    _appUser.value = _appUser.value?.copy(email = email)
  }
  if (token != null) {
    _appUser.value = _appUser.value?.copy(authToken = token)
  }
}
e

ephemient

07/24/2022, 9:43 PM
you could do just one copy,
Copy code
if (username != null || email != null || token != null) (
    val appUser = _appUser.value
    _appUser.value = appUser.copy(
        username = username ?: appUser.username,
        email = email ?: appUser.email,
        authToken = token ?: appUser.authToken,
    )
}
c

Colton Idle

07/24/2022, 9:59 PM
Cooll. okay so not far off from what i had. thanks!
f

Francesc

07/25/2022, 2:50 AM
If _appUser is a mutable state flow, consider using the update extension function to update it
i

itzik kasovitch

07/25/2022, 7:21 AM
You can use the let extension to get rid of the if something is null check
c

Colton Idle

07/25/2022, 2:07 PM
_appUser IS a mutablestateflow!