Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // A mutable class
- class Thing {
- var x = 0
- var y = 0
- set(v) {
- field = v
- for (l in listeners) {
- l()
- }
- }
- fun addChangeListener(l: () -> Unit) {
- listeners.add(l)
- }
- private val listeners = mutableListOf<() -> Unit>()
- }
- class MyViewModel: ViewModel() {
- var n1: Int = 0
- var n2: Int by mutableStateOf(0)
- var thing1: Thing by mutableStateOf(Thing())
- init {
- thing1.addChangeListener {
- println("Setting it to itself to try to trigger state change.")
- thing1 = thing1
- }
- }
- }
- @Composable
- fun TestThings(model: MyViewModel) {
- Column(Modifier.padding(20.dp)) {
- Text("n1 = ${model.n1}")
- Text("n2 = ${model.n2}")
- Text("thing1.x = ${model.thing1.x}")
- Text("thing1.y = ${model.thing1.y}")
- // As expected, changes to n1 do not trigger recomposition. `n1` is just a plain Int.
- Button(onClick = { model.n1++ }) {
- Text("Change n1")
- }
- // As expected, changes to n2 trigger recomposition. `n2` is wrapped in MutableState.
- Button(onClick = { model.n2++ }) {
- Text("Change n2")
- }
- // I didn't think this would trigger recomposition.
- Button(onClick = { model.thing1.x++ }) {
- Text("Change thing1.x")
- }
- // I thought this might, but it doesn't.
- Button(onClick = { model.thing1.y++ }) {
- Text("Change thing1.y")
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement