Question
I have created a multi module kmp app
Data
Domain
Di
Design system
Compose app
My question is for Data module where I want to implement Room Db, the problem is it requires context and passing context in Data layer seems anti pattern.
I have tried actual/expect mechanism but still its not working.
Any suggestions are valuable.
Can you share how you tried to use actual/expect and how it was failing?
d
Deep Naik
05/16/2025, 1:38 AM
Is it safe to add android context lib in the Data module?
s
Seri
05/16/2025, 2:51 PM
In your android implementation of the expect/actual
RoomDatabase.Builder<AppDatabase>
, sure. If you want to avoid that, you'll need to create your
RoomDatabase.Builder<AppDatabase>
with a
Context
closer to your application layer and then use dependency injection to bring it into the :data module
d
Deep Naik
05/19/2025, 5:03 AM
Yes, I am able to resolve this with koin androidContext().
I've injected the context from my composeApp and used in Di module.
t
Tim Karagosian
05/25/2025, 1:29 PM
@Deep Naik You will want to build the Dao and DB in the main activity. Here's some samples of my code on the Android native side that tie into the shared code implementation. The first is in my MainActivity:
Copy code
val myDao = getDatabase(applicationContext).myDao()
And this is in its own class on Android native to build the db correctly with application context passed in via main activity:
Copy code
fun getDatabase(context: Context): MyDatabase{
val dbFile = context.getDatabasePath("my_db.db")
return Room
.databaseBuilder<MyDatabase>(
context = context.applicationContext,
name = dbFile.absolutePath,
)
.setDriver(BundledSQLiteDriver())
.fallbackToDestructiveMigrationOnDowngrade()
.fallbackToDestructiveMigration()
//.enableMultiInstanceInvalidation()
//.addMigrations(MIGRATION_1_2)
.build()
}