I have Room TypeConverter
and I need to inject parameter to it\'s constructor
class RoomConverters(moshi Moshi) {
@TypeConverter
fun fromUs
I use dagger-android, and faced same problem. Solution is when creating AppDatabase
@Provides @Reusable
fun provideDatabase(context: Context, moshi: Moshi): AppDatabase =
Room.databaseBuilder(...).build().apply { AppDatabase.moshi = moshi }
AppDatabase is simple RoomDatabase:
@Database(
entities = [OrderEntity::class],
version = 1,
exportSchema = false
)
@TypeConverters(DbConverters::class)
abstract class AppDatabase : RoomDatabase() {
companion object {
lateinit var moshi: Moshi
}
abstract fun orderDao(): OrderDao
}
Then use this companion object in converter:
class DbConverters {
@TypeConverter
fun orderInfoToString(orderInfo: OrderInfo?): String? =
AppDatabase.moshi.adapter(OrderInfo::class.java).toJson(orderInfo)
@TypeConverter
fun stringToOrderInfo(value: String): OrderInfo? =
AppDatabase.moshi.adapter(OrderInfo::class.java).fromJson(value)
}
This is looking ugly, I guess, but works. Maybe using static/companion object with @Reuseable
scope is a bad idea.
Moshi, though, is provided using @Singleton
scope in AppModule, so basically live through entire application life