8

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?

gts13
  • 1,048
  • 1
  • 16
  • 29
Archie G. Quiñones
  • 11,638
  • 18
  • 65
  • 107

1 Answers1

5

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() } 
} 
Subhanshuja
  • 390
  • 1
  • 3
  • 20
Corinzio
  • 155
  • 1
  • 6