Kotlin和Room的Dagger 2错误

时间:2018-06-29 20:47:58

标签: android kotlin dagger-2

我一直在将应用重构为Kotlin,目前我正面临Dagger的奇怪错误。我试图实现MVVM设计,但因匕首错误而陷入困境。

AppModule

{ mkDerivation, base, stdenv, ... }:

AppComponent

@Module
class AppModule(val app: App) {

companion object {
    private var INSTANCE: RecorderisDB? = null

    private fun getInstance(context: Context): RecorderisDB?{
        if (INSTANCE == null) {
            synchronized(RecorderisDB::class){
                INSTANCE = Room.databaseBuilder(context.applicationContext,
                        RecorderisDB::class.java,
                        "recorderis.db")
                        .build()
            }
        }
        return INSTANCE
    }

    fun destroyInstance(){
        INSTANCE = null
    }
}

@Provides @Singleton
fun provideApp() = app

@Provides @Singleton @Nullable
fun getDB(context: Context): RecorderisDB? = getInstance(context)

@Provides @Singleton
fun provideDateVM(db: RecorderisDB): DateViewModel {
    return DateViewModel(db)
}

DateViewModel

@Singleton
@Component(modules = [(AppModule::class)])
interface AppComponent {

fun inject(app: App)

fun inject(form: Form)
}

Form.kt

class DateViewModel @Inject constructor(val dB: RecorderisDB){

fun createDate(name: String, symbol: String, date: String): Completable {
    return Completable.fromAction{ dB.getDateDao().newDate(Date(name, symbol, date))}
}

Stacktrace日志

英语不是我的母语,但是我认为这个错误与我矛盾吗?告诉我我的数据库不可为空,但正在提供BUT吗?基本上,我在AppModule中拥有我的同伴对象。

class Form : AppCompatActivity() {

@Inject
lateinit var dateVM: DateViewModel
public override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_form)
    App.graph.inject(this)

    initDialog()
    setUpRecyclerView()
 }

1 个答案:

答案 0 :(得分:2)

确切地说,问题是即使您提供RecorderisDB,您仍在注入RecorderisDB?

解决方案? Dagger仅使用@Singleton @Provides就已经为您处理了双重检查锁定。完全不需要该代码。

@Module
class AppModule(val app: App) {

    @Provides
    fun provideApp() = app

    @Provides @Singleton
    fun getDB(context: App): RecorderisDB = Room.databaseBuilder(context.applicationContext,
                        RecorderisDB::class.java,
                        "recorderis.db")
                        .build()

    @Provides 
    // @Singleton // are you CERTAIN this is singleton?
    fun provideDateVM(db: RecorderisDB): DateViewModel {
        return DateViewModel(db)
    }
}