在Kotlin上使用Rxjava将行插入Room

时间:2018-11-30 09:41:02

标签: kotlin rx-java2 android-room

本文说,我可以将Completable用作@Insert的返回类型 但是当我这样做时,发生了错误:

error: local variable pointToInsert is accessed from within inner class; needs to be declared final

AndoridX会发生此错误,因为仅从2.1版本开始才包含Rxjava返回类型支持:https://issuetracker.google.com/issues/63317956#comment25

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertPoint(pointToInsert: ControlPoint): Completable

那么,如何使这件事起作用?

1 个答案:

答案 0 :(得分:0)

由于除非使用2.1+版,否则此功能是完全不可用的,因此您可以通过为DAO制作某种适配器来使用较低版本来解决此问题:

@Dao
interface Original {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertPoint(pointToInsert: ControlPoint)

}

class AdHocCompletableAdapter(private val dao: Original) {

    fun insertPoint(pointToInsert: ControlPoint) = 
        Completable.create {
            dao.insertPoint(pointToInsert)
            it.onComplete()
        }
}

或创建一些更灵活的解决方案(例如,使用函数组合)。