Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ViewModelScoped Dependency as a constructor argument #1871

Open
mahmed1987 opened this issue May 8, 2024 · 2 comments
Open

ViewModelScoped Dependency as a constructor argument #1871

mahmed1987 opened this issue May 8, 2024 · 2 comments

Comments

@mahmed1987
Copy link

mahmed1987 commented May 8, 2024

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
Copy link
Member

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
Copy link
Author

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 .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants