Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch using inject()-function from Koin

I'm using the dependency injection framework Koin in my app. The following line of code works perfectly in my MainActivity:

private val auth: FirebaseAuth by inject()

Unfortunately, the same line of code does not work in a custom BroadcastReceiver. Android Studio marks the "inject()"-function red and tells me it is an unresolved reference (import of "org.koin.android.ext.android.inject" is marked as unused).

When I try to build it nevertheless, I got the following exception:

Error:(14, 39) Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public inline fun ComponentCallbacks.inject(name: String = ...): Lazy defined in org.koin.android.ext.android

How can I make the injection work in this class and why does it fail?

like image 420
Piwo Avatar asked Jan 18 '18 14:01

Piwo


1 Answers

The inject method you use in Activities is defined here like so:

/**
 * inject lazily given dependency for Android component
 * @param name - bean name / optional
 */
inline fun <reified T> ComponentCallbacks.inject(name: String = "") 
    = lazy { (StandAloneContext.koinContext as KoinContext).get<T>(name) }

So you can call it in classes that implement the ComponentCallbacks interface - these would be application components, like Activities or Services.

If you wish to use Koin the same way in your BroadcastReceiver, you can define another inject extension on that class with the same implementation:

inline fun <reified T> BroadcastReceiver.inject(name: String = "") 
    = lazy { (StandAloneContext.koinContext as KoinContext).get<T>(name) }
like image 198
zsmb13 Avatar answered Oct 23 '22 21:10

zsmb13