Skip to content

Instantly share code, notes, and snippets.

@magillus
Created April 11, 2019 14:11
Show Gist options
  • Save magillus/07c6b188bafd927fe9944e049e7d8343 to your computer and use it in GitHub Desktop.
Save magillus/07c6b188bafd927fe9944e049e7d8343 to your computer and use it in GitHub Desktop.
Koin helper methods for module definition with Generic types - here StateMachine is generic
///define in module
val stateMachineModule = module {
stateFactory{ TestImplStateMachine() } bind StateMachine::class
}
/// inject or get
val stateMachineTest:StateMachine<MyState> = getSm()
///class of state machine
class TestImplStateMachine : StateMachine<MyState> {
}
/**
* Declare a Factory definition for StateMachine generic type
* @param override
* @param definition - definition function
*/
inline fun <reified S> Module.stateFactory(
override: Boolean = false,
noinline definition: Definition<StateMachine<S>>
): BeanDefinition<StateMachine<S>> {
val beanDefinition = DefinitionFactory.createFactory(named<S>(), definition)
declareDefinition(beanDefinition, Options(override = override))
return beanDefinition
}
/**
* Gets instance of StateMachine for matching generic type
*/
inline fun <reified T> Scope.getSm(
scope: Scope = this,
noinline parameters: ParametersDefinition? = null
): StateMachine<T> {
return getKoin().get(StateMachine::class, named<T>(), scope, parameters)
?: error("$this is not registered - Koin is null")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment