Room TypeConverter with constructer

前端 未结 4 699
我在风中等你
我在风中等你 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:23

    You can create Room TypeConverter with constructor parameters from version 2.3.0-alpha03

    Release notes:

    Room now has APIs for providing instances of type converters such that the app can control their initialization. To mark a type converter that will be provided to Room use the new annotation @ProvidedTypeConverter

    https://developer.android.com/jetpack/androidx/releases/room#2.3.0-alpha03

    In your case you should add @ProvidedTypeConverter to RoomConverter

    @ProvidedTypeConverter    
    class RoomConverters(moshi: Moshi)
    

    Create converter at db creation time and pass it to database builder:

    val roomConverter = RoomConverters(Moshi())
    val db = Room.databaseBuilder()
             .addTypeConverter(roomConverter)
             .build()
    

    Also you can use DI framework e.g. Dagger2

提交回复
热议问题