Is it advisable to pass state objects as parameter...
# compose
r
Is it advisable to pass state objects as parameters to composable functions? If not what are the implications. I'm referring to something like this.
Copy code
@Composable
fun StyledText(
    text: State<String>,
) {
    Text(text = text.value)
}
c
I don't know the implications... BUT I do remember seeing something in the docs a while back where they tell you that you shouldn't be passing in snapshot state Types like this
r
I remember seeing something similar a long time ago but I don't remember what was said about it, other than not using it. I'm trying to discourage my team from using it but I don't have any strong points to say about that, other than losing the delegate property
👍 1
s
Pass
() -> T
instead. The reason is simple, you still get the benefit of deferred reads when you need that. But
() -> T
also allows you to pass a normal non-state object. If you use
State<String>
instead as you show above, and you don’t have a state at some call-site, you’d need to turn your normal parameter into a state just to pass into this clunky API. Don’t do it.
âś… 2
👍 1
j
z
lowercase-s “state” objects, i.e. state holder classes that have snapshot-backed state internally, yes, if there are other reasons to factor out a state holder. Uppercase-s
State
types, no, for the reasons above.
👍 3
v
Just to clarify, you still do get the benefit of deferred reads when passing
State<T>
as a parameter. It's just that passing
() -> T
is better for the benefits mentioned by Stylianos & Zach.
🦜 1
m
I want a small confirmation here to see if I understand this correctly. As per my understanding this is not defering reads:
Copy code
@Composable
fun StyledText(text: String) {
 ....
}
But these 2 are deferring reads:
Copy code
@Composable
fun StyledText(text: State<String>) {
 ....
}
Copy code
@Composable
fun StyledText(text: () -> String) {
 ....
}
Right?
👍🏻 1
v
Yes, exactly
👌 1