Home > OS >  Compose and UiState
Compose and UiState

Time:05-25

In compose the idea is to maintain composable state via UiState. Composable is recomposed every time UiState is updated. However, in some cases we can't update composable with recomposition, instead, we need to make a call. For example, with ModalBottomSheetLayout, to expand/collapse, I don't trigger recomposition, but call state object like so:

scope.launch {
    modalBottomSheetState.animateTo(ModalBottomSheetValue.Expanded)
}

Say I want to maintain bottom sheet state via UiState rather than these calls. Is that possible? I'm asking about bottom sheet as an example, but I think this is a question that can be applied to other composable components.

CodePudding user response:

You can try to use remember extension function

val modalBottomSheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)

CodePudding user response:

"If I had eight hours to write compose screen, I’d spend the first six of them reading docs" - Abraham Lincoln

Compose is supposed to not have side-effects, however, if you need them, you can use them via LaunchedEffect. So the answer to my question would be to keep boolean val isBottomSheetExpanded in my UiState and then in compose call

if (state.isBottomSheetExpanded) {
    LaunchedEffect(modalBottomSheetState) {
        modalBottomSheetState.animateTo(ModalBottomSheetValue.Expanded)
    }
} else {
    LaunchedEffect(modalBottomSheetState) {
        modalBottomSheetState.animateTo(ModalBottomSheetValue.Hidden)
    }
}
  • Related