Search code examples
androiddependency-injectionkoin

Android Koin DI - ViewModel injection


Did anybody solved injecting ViewModel with Koin ?

I am using

    def koin_version = "2.1.0"
    implementation "org.koin:koin-core:$koin_version"
    // Testing
    androidTestImplementation "org.koin:koin-test:$koin_version"

And I am trying to inject ViewModel via Koin.

I have an empty ViewModel:

class AuthViewModel
constructor(
    val authRepository: AuthRepository
) : ViewModel()
{


}

And my koin module looks like this:

val authModule = module {
    viewModel { AuthViewModel(get()) }
}

But keyword viewModel in the authModule is not recognized, nor there is a Koin import for it.

I have tried manually to import:

import org.koin.android.viewmodel.ext.android.viewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.java.architecture.ext.viewModel

But these imports are also not recognized.

Any ideas ?

Thanks


Solution

  • for that I think you will need

    implementation "org.koin:koin-androidx-viewmodel:$koin_version"
    

    in my playground project I have it configured like this:

    implementation 'org.koin:koin-android:2.0.1'
    implementation 'org.koin:koin-androidx-scope:2.0.1'
    implementation 'org.koin:koin-androidx-viewmodel:2.0.1'