InsertKoinIO / koin

Koin - a pragmatic lightweight dependency injection framework for Kotlin & Kotlin Multiplatform
https://insert-koin.io
Apache License 2.0
8.76k stars 695 forks source link

ViewModelScoped Dependency as a constructor argument #1871

Open mahmed1987 opened 1 month ago

mahmed1987 commented 1 month ago

I want to introduce a dependency in my ViewModel that is tied to the ViewModel (its life and death should work with the life and death of the ViewModel)

This code (copied from the official koin resource) works

class MyScopeViewModel : ViewModel(), KoinScopeComponent {

    override val scope: Scope = createScope(this)

    // inject your dependency
    val session by scope.inject<Session>()

    // clear scope
    override fun onCleared() {
        super.onCleared()
        scope.close()
    }
}

However this is not what I want to achieve , I want to inject the Session class as a Constructor argument like this

class MyScopeViewModel(val session:Session) : ViewModel(){

}

The above responds with the exception stating that the Session bean could not be found.

What am i missing here ?

Koin Version - 3.5.0

arnaudgiuliani commented 1 month ago

For now we can handle scope creation by field: https://insert-koin.io/docs/reference/koin-android/scope#viewmodel-scope-since-354

Another solution is in study for 3.6

mahmed1987 commented 1 month ago

yeah @arnaudgiuliani , this appears to be quite necessary to have dependencies injected that are scoped to the ViewModel itself , and not single<> (kinda like what ScopedViewModel does , but yeah would want to do that in a normal androidx.ViewModel)

A use case can be for example a facility to sort a student list in a StudentViewModel called StudentSorter(). The StudentSorter class doesn't need to survive StudentViewModel death.

Great to know that this is in the radar .