If I have a screen that displays a list of Books and I want to update the "likes" on each individual...
c
If I have a screen that displays a list of Books and I want to update the "likes" on each individual book while the screen is showing, but I also want to update the list of Books showing on the screen. What's the best route to go? Option 1: var books = mutableStateListOf<Book>() class Book(title: String, likes: Long) Option 2: var book = listOf<Book>() class Book(title: String, likes: Long){ var likes by mutableStateOf() } Option 3 var books = mutableStateListOf<Book>() class Book(title: String, likes: Long){ var likes by mutableStateOf() }
I feel like option 3 would be the route to go, but then I remember https://dev.to/zachklipp/two-mutables-dont-make-a-right-2kgp
f
I would do option 1
My choice would be to have a data class for the whole UI and in there there would be a list of Book which has those 2 attributes, name and likes. The UI class would then be observable and immutable. When you change the likes or the books you make a new UI data class with the updated content.
c
thanks. i think it'd be nice if i didn't have to use the .copy route to just update one small property on an item in the list, but I think i understand why that's not advisable.
f
using immutable classes makes things simpler - the other day you were asking about Concurrent Modification Exception on a list - having an immutable data class prevents that from happening. The cost in the copy is minor and with ART garbage collection things are much improved. And you would usually do any any such work to update the state in a background thread and then publish to the UI, so there is no UI jank
c
Hm. The CME I had the other day was using data classes. But points definitely taken! ❤️
f
right, but a data class is not by itself immutable, unless you make it so. If you have immutable classes you can't have CMEs
c
Interesting. I'm fairly certain that I don't have any mutable types and the only thing that was causing the CME was because I was searching the list on one thread, but then I was swapping out an item in the list (since it's immutable) on another thread.
f
that sounds like a mutable list
c
Isn't that option 1 though? The list is mutable but the items are not?
But anyway. I think maybe at this point I'm kinda conflating the questions because even though they seem similar they did stem from separate issues. 😁
f
option 1 is a mutable list, but the option I was discussing is to expose the UI state as an immutable data class, which has a list of Books