Search code examples
androiddependency-injectionandroid-jetpack-composedagger-2

Jetpack Compose and DI with Dagger 2


Recently I was working on a small project and thought of one thing about compose and dagger.

Usually I used Dagger with inject function that was dong everything for me but now it seems that it isn't work that way because we don't have any "object" to inject into. So my question is how to inject now? I can still create components like before but it seems that i need to provide properties by myself or create some @Composable functions that will do it for me.

So my question is how to work with DI (especially with Dagger) and Compose now?

I was looking for some articles but most are about hilt and I want to use pure dagger.


Solution

  • All in all, I ended up with this solution that I been using for a while now:

    class DaggerViewModelProvider {
    
        companion object {
            @Composable
            @Suppress("unchecked_cast")
            inline fun <reified VM : ViewModel> daggerViewModel(
                key: String? = null,
                crossinline viewModelInstanceCreator: @DisallowComposableCalls () -> VM
            ): VM {
                val factory = remember(key) {
                    object : ViewModelProvider.Factory {
                        override fun <VM : ViewModel> create(modelClass: Class<VM>): VM {
                            return viewModelInstanceCreator() as VM
                        }
                    }
                }
                return viewModel(key = key, factory = factory)
            }
        }
    }
    

    and call it from anywhere I need like this:

    val viewModel = DaggerViewModelProvider.daggerViewModel {
                authComponent.authViewModel
            }