简体   繁体   English

如何在Android Room Library中使用RxJava?

[英]How to use RxJava with Android Room Library?

I am developing in Adnroid RxJava with Room . 我正在使用RoomAdnroid RxJava进行开发。

I use retrofit to call API and update the value in database like the following code: 我使用改造来调用API并更新数据库中的值,如以下代码所示:

    override fun certifyMail(userInfo: Userinfo): Observable<Int> {
        return securityApi.certifyUserInfo(userInfo)
            .map {
            //return Observable<Status> here
                when(it.status){
                    "OK" -> {
                        it
                    }
                    else -> {
                        throw Exception(it.msg!!)
                    }
                }
            }
            .flatMap {
                userInfoDataSource.updateUserCertifyMailInfo(userInfo.account,1)
            //How to convert the return type to Observable<Int> from Int.
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
    }

When the response is OK from API, I will update the value in database like the following. 当API的响应OK时,我将更新数据库中的值,如下所示。

@Query("UPDATE certify_info SET value = :value  WHERE account = :account")
fun updateCertifyMailConfirm(account:String,value: Int):Int

But the return type of database is Int . 但是数据库的返回类型为Int How to covert it to Observable<Int> ? 如何将其隐藏到Observable<Int>

Thanks in advance. 提前致谢。

Room library can return RxJava's types. 房间库可以返回RxJava的类型。

Add implementation "androidx.room:room-rxjava2:2.2.0-rc01" library to your project implementation "androidx.room:room-rxjava2:2.2.0-rc01"库添加到您的项目中

Checkout this great article for better understanding. 查看这篇出色的文章,以更好地理解。

Also checkout Google official sample about this 还可以查看有关此内容的Google官方示例

And simply edit your updateUserCertifyMailInfo method in one of this ways (choose one that suits more): 并只需使用以下一种方法编辑updateUserCertifyMailInfo方法(选择一种更适合的方法):

With Maybe: 与也许:

@Query("UPDATE certify_info SET value = :value  WHERE account = :account")
fun updateCertifyMailConfirm(account:String,value: Int):Maybe<Int>

With Single: 单身:

@Query("UPDATE certify_info SET value = :value  WHERE account = :account")
fun updateCertifyMailConfirm(account:String,value: Int):Single<Int>

With Flowable/Observable: 具有可流动/可观察:

@Query("UPDATE certify_info SET value = :value  WHERE account = :account")
fun updateCertifyMailConfirm(account:String,value: Int):Flowable<Int>

Important! 重要! Read carefully about how every type behaves with Room Queries 仔细阅读每种类型在房间查询中的行为

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM