ankushg
06/09/2022, 12:30 AMclass Outer(val middle: Middle?)
class Middle(val inner: Inner)
interface Inner
module {
factory { Outer(getOrNull()) }
factoryOf(::Middle)
}
Depending on certain conditions, I dynamically provide an implementation of Inner
into the Koin instance.
Current Behavior:
• when Inner
is dynamically loaded, Koin can inject both Middle
and Outer
.
• when Inner
is not dynamically loaded, Koin fails to inject both Middle
and Outer
Desired behavior:
• When Inner
is not dynamically loaded and Middle
cannot be injected (because Inner
is missing), I would still like to inject Outer
using null
as the parameter value
Does anyone know how to do this? I’m guessing it might be possible with a method that’s similar to getOrNull
?ankushg
06/09/2022, 1:12 AM/**
* Get a Koin instance if available, returning `null` if we fail to create an instance (usually due to a
* missing dependency)
*
* @param qualifier
* @param scope
* @param parameters
*
* @return instance of type T or null
*/
inline fun <reified T : Any> Scope.tryGetOrNull(
qualifier: Qualifier? = null,
noinline parameters: ParametersDefinition? = null
): T? {
return try {
getOrNull(qualifier, parameters)
} catch (e: InstanceCreationException) {
<http://logger.info|logger.info>("|- Falling back to null!")
null
}
}
Would appreciate any thoughts on this — I’m sure it’s not perfect 😅