InsertKoinIO / koin

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

Strongly typed viewModel getter extensions #1995

Open chokokatana opened 1 month ago

chokokatana commented 1 month ago

Is your feature request related to a problem? Please describe.

Given the following presumed viewModel:

class CosmosDetailsVm(
    currency: KmpCurrency,
    network: KmpNetwork,
) {
…
}

and the module definition:

val kmpVmModule = module {
    viewModel { (currency: KmpCurrency, network: KmpNetwork) ->
        CosmosDetailsVm(
            currency = currency,
            network = network,
        )
    }
}

We are telling Koin there are two parameters to be passed. Sadly, users have to use the unsafe:

    private val realVm: CosmosDetailsVm by viewModel {
        parametersOf(
            intent.getParcelableExtra(ARG_CURRENCY)!!,
            intent.getParcelableExtra(ARG_NETWORK)!!,
        )
    }

This is frustrating. Using annotation reduces some of this boilerplate for the creator, but still forces consumers to carefully pass the correct parameters.

Describe the solution you'd like

Either through the knowledge provided by the annotation @InjectedParam or some magic compiler that detects the definition of input params, have Koin generate the following extension function:

inline fun ComponentActivity.injectCosmosDetailsVm(
    currency: KmpCurrency,
    network: KmpNetwork,
): CosmosDetailsVm {
    return getViewModel {
        parametersOf(currency, network)
    }
}

This changes the injection caller site to look like:

    private val mRealVm by lazy {
        injectCosmosDetailsVm(
            intent.getParcelableExtra(ARG_CURRENCY)!!,
            intent.getParcelableExtra(ARG_NETWORK)!!,
        )
    }
arnaudgiuliani commented 4 days ago

for now only @InjectParam can help you with Koin Annotations on safe type. Else wait for next gen DSL 👍