`var authState by state { AuthState() }` complaint...
# compose
c
var authState by state { AuthState() }
complaint about
Functions which invoke @Composable functions must be marked with the @Composable annotation
what should i do?
z
Can you post a larger code snippet for context?
c
Sounds like maybe they added an error message that was not there before. Is AuthState composable?
c
AuthState is my model class
Copy code
@Model
class AuthState(
    var login: String = "",
    var password: String = "",
    var token: String = ""
)
c
I thought state and model were either ors?
z
You usually use
remember
with
@Model
classes because you want to keep the same instance of the model (
state
is for when you want to change the reference itself), but it should still compile. Can you post the code around
var authState by state { AuthState() }
?
l
if AuthState is a model you very likely do not want state there. That said, I am fairly sure that this is unrelated to the error that you’re getting?
are you trying to use
state
outside of a composable function?
c
@Zach Klippenstein (he/him) [MOD] it’s just a var’s placed outside of any class @Leland Richardson [G] i use authState inside Composable methods
z
Ah, if you’re trying to call
state
for a top-level var, that’s the problem.
state
is a composable function, it can only be called from inside another composable function, just like the error says.
Copy code
// Not allowed
var foo by state { "foo" }

@Composable fun Bar() {
  // Allowed
  var bar by state { "bar" }
}
c
i migrated from dev05 (to dev09) where that was works
z
Huh, I don’t even know what
state
at a top level would me or how that would work. Curious what Leland has to say 😅
c
i replaced
by state
with
= mutableStateOf(...)
and looks like that works, but any way found compilation error https://issuetracker.google.com/issues/154867792
z
mutableStateOf
isn’t a composable function so it should be callable from anywhere.
The difference is in who “owns” the
State
instance – if you call
mutableStateOf
from the top level, it’s a global variable and owned by the process, and will never be GC’d. If you use
state
(or
remember { mutableStateOf() }
which is how
state
works under the hood), the instance is owned by the composable at that point in the composition tree, and will be GC’d if that composable ever leaves the composition.
c
ok thanks for explanation
l
yep.
state
is just shorthand for
remember { mutableStateOf(block()) }
👍🏻 1