Archie G. Quiñones
Archie G. Quiñones

Reputation: 13718

How to inject a ViewModel with Koin in Kotlin?

How do we inject ViewModel with dependency using Koin?

So For Example I have a ViewModel thats like this:

class SomeViewModel(val someDependency: SomeDependency, val anotherDependency: AnotherDependency): ViewModel()

Now the official docs here, states that to provide a ViewModel we could do something like:

val myModule : Module = applicationContext {

    // ViewModel instance of MyViewModel
    // get() will resolve Repository instance
    viewModel { SomeViewModel(get(), get()) }

    // Single instance of SomeDependency
    single<SomeDependency> { SomeDependency() }

    // Single instance of AnotherDependency
    single<AnotherDependency> { AnotherDependency() }
}

Then to inject it, we can do something like:

class MyActivity : AppCompatActivity(){

    // Lazy inject SomeViewModel
    val model : SomeViewModel by viewModel()

    override fun onCreate() {
        super.onCreate()

        // or also direct retrieve instance
        val model : SomeViewModel= getViewModel()
    }
}

The confusing part for me is that, normally you will need a ViewModelFactory to provide the ViewModel with Dependencies. Where is the ViewModelFactory here? is it no longer needed?

Upvotes: 8

Views: 13155

Answers (1)

Corinzio
Corinzio

Reputation: 155

Hello viewmodel() it's a Domain Specific Language (DSL) keywords that help creating a ViewModel instance.

At this [link][1] of official documentation you can find more info

The viewModel keyword helps declaring a factory instance of ViewModel. This instance will be handled by internal ViewModelFactory and reattach ViewModel instance if needed.

this example of koin version 2.0 [1]: https://insert-koin.io/docs/2.0/documentation/koin-android/index.html#_viewmodel_dsl

// Given some classes 
class Controller(val service : BusinessService) 
class BusinessService() 

// just declare it 
val myModule = module { 
  single { Controller(get()) } 
  single { BusinessService() } 
} 

Upvotes: 5

Related Questions