kotlinandroid-jetpack-composestatejetbrains-compose

How do I access and modify a state from a non-Composable function?


I have this Composable function that holds multiple states:

@Composable
fun MyComponent() {
    var stringState by remember { mutableStateOf("foo") }
    var booleanState by remember { mutableStateOf(false) }
    var integerState by remember { mutableStateOf(0) }
}

I now want to modify these states from a non-composable function that requests an API every second or so and then update the state in my application depending on the response.

Note that this isn't the actual component but I need an answer applicable to not just one type.

I have read the docs and read the top SO answers but none of them really matched what I was looking for.


Solution

  • Can your function return a Flow of API responses? Then you can use collectAsState():

    @Composable
    fun MyComponent(apiResponses: Flow<Response>) {
        val state by apiResponses.collectAsState(initial = ...)
    }