【问题标题】:Insert a row into Room using Rxjava on Kotlin在 Kotlin 上使用 Rxjava 在 Room 中插入一行
【发布时间】:2023-03-30 09:56:01
【问题描述】:

这篇文章说我可以使用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

那么,如何让这个东西发挥作用呢?

【问题讨论】:

    标签: kotlin rx-java2 android-room


    【解决方案1】:

    除非你使用 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()
            }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      相关资源
      最近更新 更多