https://kotlinlang.org logo
m

mon

02/07/2020, 2:46 PM
Is there a way to "detach" a value from a
@Model
so that it stops getting updated when the field it is read from changes?
c

Chuck Jazdzewski [G]

02/07/2020, 4:43 PM
I am uncertain what you are asking. When an
@Model
changes the
FrameManager
(which will be renamed, probably to
CompositionManager
) will check if it was read from any compositions and schedule the function that read it to recompose (internally by invalidating the recompose scope created by the function when it called
startRestartGroup()
). The value read from the
@Model
is not tracked after the read unless it, itself, is an
@Model
object.
l

Leland Richardson [G]

02/07/2020, 5:38 PM
I think @mon is wondering whether or not you can have a mutable property on a model that won’t trigger recompositions when you read/write to it. We don’t have an explicit mechanism for this, but it’s not hard to accomplish as is. @Model is a shallow transform, so it won’t transform nested objects.
Copy code
class ValueHolder<T>(var value: T)

@Model MyModel {
  // x will cause recompositions
  var x = 0
  private val yHolder = ValueHolder(0)
  var y: Int
    get() = yHolder.value
    set(field) = yHolder.value = field
}
Note that you can also just use
mutableStateOf
to have a single property that is “tracked”, and the rest of the class won’t be
Copy code
class MyModel {
  var x by mutableStateOf(0)
  var y = 0
}
similarly, if you had
ValueHolder
implement the property delegate operators, you could do the inverse as well:
Copy code
@Model class MyModel {
  var x = 0
  var y by ValueHolder(0)
}
m

mon

02/07/2020, 11:38 PM
Thank you, I think
by mutableStateOf
is what I need