Reputation: 3221
I just started using Koin lib in an android (to replace Dagger 2) project which was prepared for tests. I have an issue with the android app context in module:
val M = module {
val ctx = androidApplication() //here error
}
Koin is started in App class:
import android.app.Application
import android.content.Context
import org.koin.android.ext.android.startKoin
class App : Application() {
override fun onCreate() {
super.onCreate()
startKoin(this, listOf(M))
}
}
I get log:
D/App: onCreate()
I/KOIN: [context] create
E/KOIN: [ERROR] - Error while resolving instance for class 'android.app.Application' - error: org.koin.error.NoBeanDefFoundException: No compatible definition found for type 'Application'. Check your module definition
and the app crashes. Did I miss something in the configuration of Koin? In the target project, I have a few modules which deeply depend on application context. And I don't want to use a global reference to this context.
Upvotes: 3
Views: 10612
Reputation: 7220
I had fix this problem to add all my viewModels
to the Koin module
.
Upvotes: 1
Reputation: 6024
Try not to create a val
for the applicationAndroid()
context but use it directly inside the factory/single closure as a parameter for one of your dependencies.
What I'm doing in my project is something like:
val appModule = module(override = true) {
factory<Navigator> { MyNavigator(androidApplication()) }
}
where the MyNavigator class is:
class MyNavigator(private val context: Context): Navigator {
override fun goToDetail(detailId: String) {
context.startActivity(DetailActivity.getIntent(context, detailId))
}
}
p.s.: I did also some experiments with Koin 1.0.0 and I noticed that you can also write something like:
val appModule = module(override = true) {
factory<Navigator> { MyNavigator(get()) }
}
That get()
will retrieve the context for you even if there's no dependency in the graph for a Context instance; neither a factory nor a singleton. It might be that Koin does something behind the scenes. I tried to use it with different type of dependencies and it aways works.
Upvotes: 4
Reputation: 945
Solution is easy but not so obvious.
Somehow Android Studio imports standalone startKoin function instead of specific android function.
So you had to replace
import org.koin.standalone.StandAloneContext.startKoin
To
import org.koin.android.ext.android.startKoin
in Application
class
Do tell if this works or not.
Upvotes: 6