Hello, I have a global `Coroutines` (img1)to read ...
# compose-desktop
u
Hello, I have a global
Coroutines
(img1)to read something(?), when it's not null ,I want send this to a function`@Composable` for update variables(
mutableStateOf
) ,How can I achieve? thanks!
g
You cannot send anything to a composable function, but you can update some state which is used by this composable function, using mutableStateOf or Compose
but it really depends how this receive() function is used, if it called from Composable function, it would be better to have some kind ViewModel/Repository for it and use it from you composable code
u
Thanks! I was thinking of something like broadcasting
g
Yes, usage of StateFlow or mutableStateOf would allow to recompose your UI with new data
u
Yes,I understand your suggestion, before: I think about move
mutableStateOf
var from fun scope to class scope(img1) , crash!; Now : I tried let the
mutableStateOf
var pointing a other var which in common scope(img2), brilliant!
Thanks a lot!❤️
g
You shouldn’t wrap it to remember, you can just use state directly if it some shared state
remember is used to remember some object to keep it between compose recompositions
but if you declare mutableStateOf somewhere outside of composable function, no need to worry about missing it, it will just have the same lifecycle as class where it declared (or global if it top-level function)
u
Could you give a good example?Thanks! when I remove
remember
,it's crash:
g
Crashes or not compiling?
u
not compiling😭
g
No, you should always use remember inside of composable
but in this case you will not be able to update it from outside
what I mean is:
Copy code
val hardVersion = mutableStateOf("test")

@Composable
fun fragmentBox1() {
    TextField(value  = hardVersion.value)
}

fun receive() {
   GlobalScope.launch {
     hardVersion.value = "something"
   }
}
u
Sorry,I can't find get() from
MutableState
oh! value?
g
yep, sorry, value
.get() is not from Compose %)
Updated example with value
u
Thank you very much, you are very patient!❤️
g
Haha, no problem, hope it helpful Just remember it’s more an example, and for real code I would rather abstract all those state loading and updating to repository/view model
u
Mean this? Move any var to RuntimeContent such as hardVersion?
g
If they updated from outside of composable functions, yes, otherwise it's better to keep them internal
u
Yes it is!I understand.Thanks a lot!
t
FYI, you need
.value
because you use
mutableStateOf
directly instead of as a delegate:
Copy code
var x = mutableStateOf("hello")
Text(text = x.value)
x.value = "world"
vs.
Copy code
var x by mutableStateOf("hello")
Text(text = x)
x = "world"