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

Colton Idle

08/07/2022, 2:56 AM
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

Francesc

08/07/2022, 6:21 AM
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

Colton Idle

08/08/2022, 6:13 AM
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

Francesc

08/08/2022, 3:07 PM
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

Colton Idle

08/08/2022, 3:10 PM
Hm. The CME I had the other day was using data classes. But points definitely taken! ❤️
f

Francesc

08/08/2022, 3:12 PM
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

Colton Idle

08/08/2022, 3:24 PM
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

Francesc

08/08/2022, 3:26 PM
that sounds like a mutable list
c

Colton Idle

08/08/2022, 3:40 PM
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

Francesc

08/08/2022, 3:42 PM
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
3 Views