https://kotlinlang.org logo
#compose
Title
# compose
s

Sheroz Nazhmudinov

04/04/2020, 6:49 PM
Hey there, can smbd please explain me, what’s the purpose of
state {…}
? Is it smth that’s used to control the state of the UI? If possible with an example, pls. AFAIK, the source of truth for the UI should be a model class (Model annotated class). Correct me if I’m wrong here.
a

Adam Powell

04/04/2020, 7:02 PM
It's an alias for
Copy code
remember { mutableStateOf(...) }
mutableStateOf<T>(initialValue)
returns a
MutableState<T>
, which also implements the read-only interface
State<T>
. The returned implementation is backed by the same
@Model
infrastructure, so changing its
.value
property has the same effect as changing a property of a
@Model
class
it also supports property delegation, so you can write
Copy code
var myState by state { 0 }
and simply reference
myState
as an
Int
var that will be observed by the composition when it changes
it's useful when you don't need a whole new class or type as a holder of mutable state
s

Sheroz Nazhmudinov

04/04/2020, 7:08 PM
oh I see, that clears it out for me. I wasn’t sure if I have to create Model class for every state of my component. Thanks 👍
a

Adam Powell

04/04/2020, 7:11 PM
nope! That would be kind of a pain, and
MutableState<T>
would be one of the first things you'd write to avoid having to do that all over, so it's built-in 🙂
s

Sheroz Nazhmudinov

04/04/2020, 7:12 PM
exactly 😄 thanks for the clarification!
👍 1
a

Adam Powell

04/04/2020, 7:15 PM
Definitely check out state hoisting patterns though, a bunch of private state in your composables can start to get a bit difficult to work with as your app grows.
👍 2