Room TypeConverter with constructer

前端 未结 4 692
我在风中等你
我在风中等你 2021-02-14 20:27

I have Room TypeConverter and I need to inject parameter to it\'s constructor

class RoomConverters(moshi Moshi) {

    @TypeConverter
    fun fromUs         


        
4条回答
  •  囚心锁ツ
    2021-02-14 21:13

    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

提交回复
热议问题