Is someone using Kodein-DI with Compose? I’m curio...
# kodein
n
Is someone using Kodein-DI with Compose? I’m curious how are you providing and scoping VMs in Composables? @romainbsl is any support planned?
j
I am using it. The VM is basically linked to the composable its in
so not really caring about lifecycle
also not using jetpack viewmodels but custom one
It might look weird, but I use it with a react application and sort of gave them the same architecture:
Copy code
val DIAmbient = ambientOf { DI {} }

@Composable
inline fun <reified T : Any> instance(): DIProperty<T> = DIAmbient.current.instance()

@Composable
inline fun <reified A : Any, reified T : Any> instance(arg: A?): DIProperty<T> = arg?.let {
    DIAmbient.current.instance<A, T>(arg = it)
} ?: instance()

object EmptyProps

@Composable
inline fun composeSubDI(
    crossinline diBuilder: DI.MainBuilder.(scope: CoroutineScope) -> Unit,
    props: Any = EmptyProps,
    noinline content: @Composable () -> Unit
) {
    val currentDi = DIAmbient.current
    val composedScope = remember(props) {
        CoroutineScope(Dispatchers.Main)
    }
    onDispose {
        composedScope.cancel()
    }
    Providers(
        DIAmbient provides remember(props) {
            subDI(currentDi) { diBuilder(composedScope) }
        },
        children = content
    )
}
and then in practice:
Copy code
fun exampleComponentBuilder(): DI.MainBuilder.(scope: CoroutineScope) -> Unit = {
    import(exampleModule())
}

@Composable
fun exampleComponent() {
    composeSubDI(diBuilder = exampleComponentBuilder()) {
        val viewModel by instance<ExampleContract.ViewModel>()
        val viewState = viewModel.viewState.collectAsState(AndroidUiDispatcher.Main).value
        OutlinedButton(onClick = viewModel::onButtonClicked) {
            Text(viewState.buttonText, color = MaterialTheme.colors.primary)
        }
    }
}
so whenever you call composeSubDI, you create a sub di component
so you can nest whatever
it is injecting a coroutine scope into the components, so that will be cancelled whenever you leave the composable
235 Views