Reputation: 3258
Imagine the following object
data class CourseState(
val key:Int=0,
val name:String="",
val courses:Courses=Courses())
Implementing the following pattern
private val _courseState = mutableStateOf(CourseState())
val courseState: State<CourseState> = _courseState
I can trigger recomposition of my UI by calling:
_courseState.value = CourseState()
but not by calling:
_courseState.value.courses.addCourse(Course("some course))
this is a bit frustrating because even though the object has clearly changed I am forced to create a whole new instance of the parent object in order to elicit a small change in it.
Now, I know than behind the scenes Compose is using the .equals()
method in order to acertain if it should recompose the layout so I ve had a few ideas on how to achieve the desired behaviour.
overwrite the equals
method: it would imply a bit of boilerplate code and it would have to be done for the entire set of nested classes that make up my object. this might work but seems dangerous and cumbersome.
use a clone
method or a constructor that accepts an instance of its own class as a parameter to create an identical copy of my object that would nevertheless represent a new instance that I can modify and then pass as the mutable state value. sounds easier than the previous optoin but elegance is something different
dive deep into the State and MutableState classes and find out if there is a way to make them behave as I want. I am relying on some of you to have done this before so I dont have to XD
Let me know what you think or if there is some other ovbious solution that has just eluded me so far
Upvotes: 10
Views: 5535
Reputation: 7278
There are two options I would consider:
copy
, it's quite easy, it will add some overhead though.State
, otherwise you can use Flow
or LiveData
. I suppose that your Courses
class contains some List
to which
you are adding items. Make it a
mutableStateListOf(),
whenever you add something there, composables that use it should
recompose automatically.Upvotes: 5