Saher Al-Sous
04/02/2024, 8:31 AMcommonMain to startKoin.
This file contains the expect value that will return the SqlDriver for each platform, and the needed implementation to communicate with the database from commonMain.
expect val dbModule: Module
val repoModel = module {
single<DbRepository> {
DbRepository(get<SqlDriver>())
}
}
fun initKoin() = startKoin {
modules(
dbModule,
repoModel
)
}
I found out that each platform have an Issue, so I decided to focus on one platform at a time.
the problem of the Android platform is that you can't get the context needed for the AndroidSqliteDriver.
actual val dbModule: Module = module {
single<SqlDriver> {
AndroidSqliteDriver(Kos.Schema, androidContext(), "Kos")
}
}
for Android, you need the context to initialize the driver, but you have no way to inject it. since I'm starting Koin from commonMain, I couldn't find a way to get the android context from the Application class. I tried this way:
class MyApp: Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MyApp)
}
}
}
also this way
class MyApp: Application() {
override fun onCreate() {
super.onCreate()
koinApplication {
androidContext(this@MyApp)
}
}
}
and even this way
class MyApp: Application() {
override fun onCreate() {
super.onCreate()
loadKoinModules(
module {
single { this@MyApp }
}
)
}
}
and I always get an error...
Caused by: org.koin.core.error.KoinAppAlreadyStartedException: A Koin Application has already been started
Caused by: org.koin.android.error.MissingAndroidContextException: Can't resolve Context instance. Please use androidContext() function in your KoinApplication configuration.how is it possible to get android context for SqlDelight driver within kmp using Koin?
Saher Al-Sous
04/02/2024, 10:30 AMarnaud.giuliani
04/02/2024, 11:42 AMandroiContext() to your startKoin sectionSaher Al-Sous
04/02/2024, 5:16 PMarnaud.giuliani
04/03/2024, 7:58 AMSaher Al-Sous
04/03/2024, 8:51 AMlateinit for now. without Koin inside Android.arnaud.giuliani
04/03/2024, 10:56 AMdeclare() to add an object inside the current contextSaher Al-Sous
04/03/2024, 2:11 PMclass MyApp: Application() {
override fun onCreate() {
super.onCreate()
val module = module {
single { applicationContext }
}
getKoin().declare(
module
)
}
}
and this
class MyApp: Application() {
override fun onCreate() {
super.onCreate()
getKoin().declare(
applicationContext
)
but I got same error on both ways:
Copy codejava.lang.IllegalStateException: KoinApplication has not been started
arnaud.giuliani
04/03/2024, 4:00 PMkoin.declare(context)arnaud.giuliani
04/03/2024, 4:00 PMSaher Al-Sous
04/03/2024, 6:36 PM@SuppressLint("StaticFieldLeak")
lateinit var androidContext: Context
actual val dbModule: Module = module {
single<Context> { androidContext }
single<SqlDriver> {
AndroidSqliteDriver(ReminderDb.Schema, get(), "ReminderDb")
}
}
class MyApp: Application() {
override fun onCreate() {
super.onCreate()
androidContext = applicationContext
}
}