Mikael Alfredsson
06/25/2020, 9:47 AMby state
or mutableStateOf
together with remember
, both of them reassign the datamodel to a wrapped variable inside the @Compose scope and i’m not sure how to mutate the data class and force a refresh.mon
06/25/2020, 9:58 AMMutableState
delegates. So before if you had var foo = Foo()
in your @Model
class, you need to change that to var foo by mutableStateOf(Foo())
. Then you use this class the same way as before.
state
is a shortcut to remember { mutableStateOf(e) }
and remember
is only meaningful in a @Composable
so you can't use that delegate in a model class.Mikael Alfredsson
06/25/2020, 10:06 AM@Model
data class Model(
var loading: Boolean = true
)
to
class Model(
loading: Boolean = true
) {
var loading by mutableStateOf(loading)
}
Which (if this is correct) makes data classes unsuitable for compose models?mon
06/25/2020, 10:14 AMMutableState<Boolean>
but the usage would become weirdgildor
06/25/2020, 10:39 AMmakes data classes unsuitable for compose modelsMutable data class already not the best choice in general
Mikael Alfredsson
06/25/2020, 10:50 AMgildor
06/25/2020, 11:10 AMclass Model {
var loading by mutableStateOf(false)
}
fun someInit(model: Model) {
model.apply {
loading = true
}
}
Mikael Alfredsson
06/25/2020, 11:12 AMapply
the changes directly when you create the instance the first time.Adrian Blanco
06/25/2020, 12:16 PMgildor
06/25/2020, 1:46 PMLeland Richardson [G]
06/25/2020, 4:53 PMState<MyDataClass>
and then instead of mutating the data class, you would use something like .copy(…)
to produce a new one and assign the state object to the new valueclass Foo(val bar by someDelegate(bar))
Mikael Alfredsson
06/26/2020, 8:25 AMLeland Richardson [G]
06/26/2020, 4:50 PMval x = mutableStateOf<Thing>(someThing)
Right now there is extra work you need to do in order to assign x.value outside of the main thread, but there is nothing about x
that says a composition has to exist or that it has to do with composition at all.
If you want to assign it outside of the main thread, right now you will need to use FrameManager.framed { x.value = newValue }
BUT, this is changing. We just landed a big refactor to the way all of this works and now FrameManager.framed
is not needed and you can assign x.value
in any thread at any time. You can see the change here: https://android-review.googlesource.com/c/platform/frameworks/support/+/1326201
You may be a little bit confused because state { someThing }
is a composable call and can only happen inside of a composition, but mutableStateOf
has no such constraint