android - Android 房间交易如何完成返回

标签 android kotlin android-room android-architecture-components

我需要你的帮助。

我有保存一些配置的 dao 接口(interface):

@Dao interface ConfigDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(config: Config)

    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun update(config: Config)

    @Query("select * from T_CONFIG where isSelected = :isSelected")
    fun getConfig(isSelected: Boolean): Single<Config>

    @Query("select * from t_config")
    fun getConfigAll(): LiveData<MutableList<Config>>

    @Query("update T_CONFIG set isSelected = :isSelected where idEnvironment = :id")
    fun updateConfigById(id: String, isSelected: Boolean):Completable

    @Transaction
    fun updateConfigTransaction(configSelected: Config){

        if (configSelected.idEnvironment == Environtment.Type.PRD.toString()){
            updateConfigById(Environtment.Type.PRD.toString(), false)
            updateConfigById(Environtment.Type.DEV.toString(), true)
        }else{
            updateConfigById(Environtment.Type.PRD.toString(), true)
            updateConfigById(Environtment.Type.DEV.toString(), false)
        }
    }
}

我需要知道交易何时完成(成功或错误)。 我尝试从 io.reactivex 实现 Completable,但这是不可能的。

最佳答案

自房间 2.1.0 起

Additional Async Support: DAO methods annotated with @Insert, @Delete or @Update, along with @Query containing INSERT, DELETE or UPDATE statements, now support Rx return types Completable, Single, Maybe, and Guava's return type ListenableFuture, and they can also be suspend functions.

来源:https://developer.android.com/jetpack/androidx/releases/room#2.1.0

旧版本

将接口(interface)更改为抽象类。您必须在所有没有实现的方法前加上abstract 前缀。然后:

abstract class ConfigDao(private val db: MyDatabase) {

    private val scheduler = Schedulers.from(db.queryExecutor)

    // Make sure the method is open so Room can generate the transaction handling code.
    @Transaction
    open fun updateConfigTransaction(configSelected: Config){
        // ...
    }

    fun updateConfigTransactionAsync(configSelected: config): Completable {
        return Completable
            .fromAction { updateConfigTransaction(config) }
            .subscribeOn(scheduler)
    }
}

subscribeOn(db.queryExecutor) 确保查询与返回 RxJava 类型的所有其他 DAO 方法在同一线程上运行。将 MyDatabase 构造函数参数替换为您的数据库类。

关于android - Android 房间交易如何完成返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55146430/

相关文章:

android - 如何切换电话、电话扬声器、耳机或蓝牙设备的音频输出

android - Android 分页中的 DataSource.Factory 不提供 toLiveData

android - 迁移以将新数据行插入 Room DB

android - 如何防止触摸时出现软键盘

android - Android 上的默认 PCM 格式

java - 列出我的应用程序中 Assets 目录中的所有文件和文件夹(还有子文件夹),并检查 Assets 是文件还是文件夹

android - Jetpack 撰写 : Content color of TabRow

android - 修剪字符串函数中的 "it <= ' '"是什么意思

gradle 同步成功时,Kotlin 多平台无法解析引用

android - 房间livedata : crash on launch