Sebastien Leclerc Lavallee
10/17/2022, 4:06 PMdata class UserProfile(var name: String, var email: String, var password: String)
Inside my view model, I have something like that:
class ViewModel {
var userProfile by mutableStateOf(UserProfile())
}
And now I use it like that:
fun EditProfileScreen(viewModel: ViewModel) {
TextInput(value = viewModel.userProfile.email, attrs = {
onInput { viewModel.userProfile.email = it.value }
}
}
Now, from what I experienced / understand, if I modify a field from my user profile, I can’t modify it directly like I did.
I would have to do something like that:
viewModel.userProfile = viewModel.userProfile.copy(email = newEmail)
I need to copy the whole object because Compose won’t be able to detect a change and won’t trigger a recompose. And when copying, it’s a new object and this will recompose.
Now is the copy way of doing thing would be the best way? Or should I do expand my UserProfile with multiple state like:
class ViewModel {
private var userProfile = UserProfile()
var email by mutableStateOf(userProfile.email)
var name by mutableStateOf(userProfile.name)
}
And edit them directly and when I click save, I would get the current value from all states.
Or have states as read only and then have setter function to update the main class:
val email by mutableStateOf(userProfile.email)
private set
fun setEmail(newEmail) {
userProfile.email = newEmail
email = newEmail
}
Or is there any other way of doing this that I don’t think of?
Thanks! 🙂Sebastien Leclerc Lavallee
10/17/2022, 4:13 PMrocketraman
10/17/2022, 10:02 PMvar
with val
in UserProfile
. Its perfectly fine to use the copy
method to update the view model.rocketraman
10/17/2022, 10:04 PMrocketraman
10/17/2022, 10:05 PMSebastien Leclerc Lavallee
10/17/2022, 10:10 PMUserProfile
from var
to val
should not change anything mutable state wise but it will force me to use the copy
function on my mutable staterocketraman
10/17/2022, 10:10 PMSebastien Leclerc Lavallee
10/17/2022, 10:12 PM