Passing State value, or State, as Composable function parameter

Viewed 568

In a Composable function, I can pass as parameter the State, or the value of the State. Any reason for preferring to pass the value of the State, instead of the State?

In both cases, the composable is stateless, so why should I distinguish both cases?

1 Answers

It's possible to pass state's value. For example:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val isLoading = mutableStateOf(false)
        val onClickAtButton = {
            lifecycleScope.launch(Dispatchers.Main) {
                isLoading.value = true
                withContext(Dispatchers.IO) {
                    //Do some heavy operation live REST call
                }
                isLoading.value = false
            }
        }

        setContent {
            MyComposable(isLoading.value, onClickAtButton)
        }
    }
}


@Composable
fun MyComposable(
    isLoading: Boolean = false,
    onClickAtButton: () -> Unit = {}
){

    Box(modifier = Modifier.fillMaxSize(){
    
        Button(onClick = onClickAtButton)

        if(isLoading){
            CircularProgressIndicator()
        }
    }
}

Hope it helps somebody.

Related