Advertisement
rnikander

mutable objects and jetpack compose

Dec 15th, 2020
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. // A mutable class
  2. class Thing {
  3. var x = 0
  4. var y = 0
  5. set(v) {
  6. field = v
  7. for (l in listeners) {
  8. l()
  9. }
  10. }
  11.  
  12. fun addChangeListener(l: () -> Unit) {
  13. listeners.add(l)
  14. }
  15. private val listeners = mutableListOf<() -> Unit>()
  16. }
  17.  
  18. class MyViewModel: ViewModel() {
  19. var n1: Int = 0
  20. var n2: Int by mutableStateOf(0)
  21. var thing1: Thing by mutableStateOf(Thing())
  22.  
  23. init {
  24. thing1.addChangeListener {
  25. println("Setting it to itself to try to trigger state change.")
  26. thing1 = thing1
  27. }
  28. }
  29. }
  30.  
  31. @Composable
  32. fun TestThings(model: MyViewModel) {
  33. Column(Modifier.padding(20.dp)) {
  34. Text("n1 = ${model.n1}")
  35. Text("n2 = ${model.n2}")
  36. Text("thing1.x = ${model.thing1.x}")
  37. Text("thing1.y = ${model.thing1.y}")
  38.  
  39. // As expected, changes to n1 do not trigger recomposition. `n1` is just a plain Int.
  40. Button(onClick = { model.n1++ }) {
  41. Text("Change n1")
  42. }
  43. // As expected, changes to n2 trigger recomposition. `n2` is wrapped in MutableState.
  44. Button(onClick = { model.n2++ }) {
  45. Text("Change n2")
  46. }
  47. // I didn't think this would trigger recomposition.
  48. Button(onClick = { model.thing1.x++ }) {
  49. Text("Change thing1.x")
  50. }
  51. // I thought this might, but it doesn't.
  52. Button(onClick = { model.thing1.y++ }) {
  53. Text("Change thing1.y")
  54. }
  55. }
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement