Deep Patel
07/01/2024, 11:30 PMDeep Patel
07/01/2024, 11:31 PMactual val dbModule = module(createdAtStart = true) {
single<AppDatabase> {
DatabaseFactory(androidContext()).createRoomDatabase()
}
}
Wish I could do that in the constructorPedro Francisco de Sousa Neto
07/02/2024, 6:48 PM@Module
class ExpertModule {
@Factory
internal fun getContext(): Context {
val koin = GlobalContext.get()
return koin.get<Context>()
}
}
I didn't tested. Can you check it @Deep Patel?Caleb Cook
07/04/2024, 12:32 AMcontext = get()
which according to the bottom of this page will resolve the closest context definition. If you look at the definition of androidContext(), you'll also see it just wraps a call to get() in a try catch to throw an exception with more useful messaging. Something like this should work ->
@Single
fun providesAppDatabase(context: Context) : AppDatabase = DatabaseFactory(context).createRoomDatabase()
arnaud.giuliani
07/11/2024, 7:14 AMDeep Patel
07/15/2024, 4:46 PMcontext
since that’s an Android Specific thing, How can I setup my factory such that it’s provided with a context
when created in androidMain
, but not anywhere else it’s created?Deep Patel
07/15/2024, 4:47 PMdependencies {
// Koin
add("kspCommonMainMetadata", libs.koin.ksp.compiler)
}
blakelee
07/15/2024, 6:09 PMfun initKoin(appDeclaration: KoinAppDeclaration? = null)
That way in my App class I can do this
initKoin {
androidContext(this@EventsApp)
}
iOS doesn’t care about a context so I just don’t pass anything in. Afterwards just invoke the method you passed in inside of the startKoin
methodblakelee
07/15/2024, 6:16 PM@Single
expect class AppDatabaseFactory {
fun createAppDatebase: AppDatabase
}
@Single
fun provideAppDatabase(appDatabaseFactory: AppDatabaseFactory): AppDatabase = appDatabaseFactory.createAppDatabase()
In your androidMain you can do this
@Single
actual class AppDatabaseFactory actual constructor() : KoinComponent {
private val context: Application by inject()
actual fun createAppDatabase(): AppDatebase = AppDatabase(context)
}
blakelee
07/15/2024, 6:16 PM