Is it possible to have viewmodel's scoped to the b...
# koin
a
Is it possible to have viewmodel's scoped to the bottom sheet's in jetpack compose ? or can we have a custom scope which creates and destroys on bottom sheet show/dismiss ?
Tried this and it works In Module:
Copy code
scope(bottomSheetScope) {
            scopedOf(::DeleteAccountBottomSheetVM)
        }
and the composable
Copy code
val bottomSheetScope = named("BottomSheetScope")

@OptIn(ExperimentalMaterial3Api::class)
@Composable
inline fun <reified T : ViewModel> MyModalBottomSheetHolder(
    modifier: Modifier = Modifier,
    showSheet: Boolean,
    skipPartiallyExpanded: Boolean = false,
  
    crossinline dismissSheet: @DisallowComposableCalls T.() -> Unit,
    windowInsets: WindowInsets = BottomSheetDefaults.windowInsets.exclude(WindowInsets.navigationBars),
    noinline doOnceWhenContentIsShown: (() -> Unit)? = null,
    noinline dragHandle: @Composable (() -> Unit)? = { CustomBottomSheetDragHandle() },
    crossinline content: @Composable T.() -> Unit,
) {
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded)
    val scope = rememberCoroutineScope()
    val koinScope =
        LocalKoinApplication.current.getOrCreateScope("BottomSheetScopeId", bottomSheetScope)

    if (showSheet) {
        val viewModel: T = remember {
            koinScope.get()
        }

        if (doOnceWhenContentIsShown != null) {
            LaunchedEffect(Unit) { doOnceWhenContentIsShown() }
        }
        ModalBottomSheet(
            modifier = modifier
                .padding(top = 24.dp)
                .fillMaxWidth(),
            onDismissRequest = {
                scope.launch { sheetState.hide() }.invokeOnCompletion {
                    if (!sheetState.isVisible) {
                        with(viewModel) {
                            dismissSheet()
                            viewModel.viewModelScope.cancel()
                            koinScope.close()
                        }
                    }
                }
            },
            sheetState = sheetState,
            contentColor = contentColor,
            containerColor = containerColor,
            windowInsets = windowInsets,
            dragHandle = dragHandle,
            shape = RoundedCornerShape(topStart = 32.dp, topEnd = 32.dp),
        ) {
            with(viewModel) {
                content()
            }
            Spacer(
                modifier = Modifier
                    .height(
                        36.dp,
                    ),
            )
        }
    }
}
👍🏾 1
👍 1