Koin: Add support for inject() in android broadcast receivers

Created on 20 Sep 2018  路  4Comments  路  Source: InsertKoinIO/koin

Is your feature request related to a problem? Please describe.
Not easy way to inject dependencies for broadcast receivers

Describe the solution you'd like
Add below functions solve the problem:

inline fun <reified T : Any> BroadcastReceiver.inject(
        name: String = "",
        scope: Scope? = null,
        noinline parameters: ParameterDefinition = emptyParameterDefinition()
) = lazy { get<T>(name, scope, parameters) }

inline fun <reified T : Any> BroadcastReceiver.get(
        name: String = "",
        scope: Scope? = null,
        noinline parameters: ParameterDefinition = emptyParameterDefinition()
): T = getKoin().get(name, scope, parameters)

fun BroadcastReceiver.getKoin(): KoinContext = (org.koin.standalone.StandAloneContext.koinContext as KoinContext)

Describe alternatives you've considered
Implement interface KoinComponent (as @roccadev metoined)

Target Koin project
Koin-android 1.0.+ ?

question

Most helpful comment

It's a bit hidden in the full documentation, but you can get access to inject, get and getKoin in any class by implementing the interface KoinComponent

All 4 comments

It's a bit hidden in the full documentation, but you can get access to inject, get and getKoin in any class by implementing the interface KoinComponent

@roccadev Yes but Activities & Services have such functionally.

Those methods have been added as extension functions to the ComponentCallbacks interface, which is implemented by Activity, Service and Fragment, so not BroadcastReceivers. I guess this has been done as convenience to avoid always implementing KoinComponent in the above classes, although it's a copy-paste of the KoinComponent extension functions, and using ComponentCallbacks as receiver covers most of the Android components. Supporting BroadcastReceivers would mean needing to maintain another copy of the functions.
Just a guess though, surely the dev could give you an official response.

Or just tag your class with KoinComponent interface to unlock koin-android extensions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

erikhuizinga picture erikhuizinga  路  3Comments

fmobus picture fmobus  路  4Comments

guymclean picture guymclean  路  3Comments

sankarsana picture sankarsana  路  4Comments

hkelidari picture hkelidari  路  3Comments