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

Support default value in constructor DSL #1853

Open wiryadev opened 2 months ago

wiryadev commented 2 months ago

Is your feature request related to a problem? Please describe. For Android Viewmodel, i expose nullable coroutine scope in the constructor so that i can pass my own dispatcher for testing and use default implementation on the real app. So the class will look like this

class LoginViewModel(
    private val loginUseCase: LoginUseCase,
    coroutineScope: CoroutineScope? = null,
) : ViewModel()

And then i can use it like this:

stateIn(
    scope = coroutineScope ?: viewModelScope,
    started = SharingStarted.WhileSubscribed(5000),
    initialValue = false,
)

Unfortunately, if we use constructor DSL, either

  1. it will crash due to missing CoroutineScope definition, or
  2. it will retrieve whatever coroutinescope that is declared that is not meant to be for that class.

Either way, we have to go back to Koin DSL:

viewModel { LoginViewModel(get()) }

It's not a problem when the class only needs few deps, but could become bloated by get() if there are many deps.

Describe the solution you'd like Add support in constructor DSL to use default value provided in the class declaration.

eschoenawa commented 1 week ago

This is needed.

The default value is especially relevant for injecting coroutine Scopes.