Question I have created a multi module kmp app D...
# multiplatform
d
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.
s
Are you using Room 2.7.0 or newer, which supports KMP? And have you read through the Room KMP guide here? https://developer.android.com/kotlin/multiplatform/room
Can you share how you tried to use actual/expect and how it was failing?
d
Is it safe to add android context lib in the Data module?
s
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
Yes, I am able to resolve this with koin androidContext(). I've injected the context from my composeApp and used in Di module.
t
@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()
}