Is someone using Kodein-DI with Compose? I’m curio...
# kodein
Is someone using Kodein-DI with Compose? I’m curious how are you providing and scoping VMs in Composables? @romainbsl is any support planned?
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 {} }

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

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

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) {
    onDispose {
        DIAmbient provides remember(props) {
            subDI(currentDi) { diBuilder(composedScope) }
        children = content
and then in practice:
Copy code
fun exampleComponentBuilder(): DI.MainBuilder.(scope: CoroutineScope) -> Unit = {

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