koin icon indicating copy to clipboard operation
koin copied to clipboard

Support default value in constructor DSL

Open wiryadev opened this issue 2 months ago • 1 comments

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.

wiryadev avatar Apr 13 '24 07:04 wiryadev