I am learning the basics of Kotlin and Composables. My use case is very simple, I have a global variable:
var globalValue : Int = 1
Then I have this composable:
@Composable
fun SomeView(modifier: Modifier = Modifier) {
...some Text() printing globalValue
When I change the value of the globalValue
I would like SomeView() to get called.
I have tried the by remember
and using the globalValue
as parameter to the Composable, but I seem to miss the point, nothing gets updated.
Any help is appreciated!
You should use State
to update the composable when the value of the variable changes, So you can simply use mutableStateOf
like below:
val globalValue = mutableStateOf(1)
So you need read and write to this state using value
property for example to set this variable to 10 you can write this:
globalValue.value = 10
if you want to use your globalVariable without calling .value
you can simply use delegation for the property using by
keyword.
var globalValue by mutableStateOf(1)
Now you can set the variable as an normal Int
variable.