quealegriamasalegre
quealegriamasalegre

Reputation: 3258

How to trigger recomposition when only a property of an object changes Jetpack-Android

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.

  1. 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.

  2. 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

  3. 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

Answers (1)

Jan B&#237;na
Jan B&#237;na

Reputation: 7278

There are two options I would consider:

  1. As you mention, create new instances of your objects for every change. With data classes and copy, it's quite easy, it will add some overhead though.
  2. Make all the data that you need to change observable. If you only want to observe them from compose, make it 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

Related Questions