Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 568
Archie G. Quiñones Avatar asked May 24 '19 01:05

Archie G. Quiñones


1 Answers

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() } 
} 
like image 72
Corinzio Avatar answered Nov 17 '22 11:11

Corinzio