如何使用Room Db返回Rx单笔交易? [英] How to return a Rx Single transaction using Room Db?

查看:64
本文介绍了如何使用Room Db返回Rx单笔交易?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设存在一个具有以下两种方法的Dao类:

Suppose there is a Dao class with the following two methods:

1)

delete(items: List<Item>): Completable

2)

 insert(items: List< Item >): Single<List<Long>>

如何将它们链接到Dao类中的以@transaction方法中,然后返回"insert method"的结果?

How can I chain them into a @transaction method in Dao class starting with ‘delete method’ and then returning ‘insert method’ result?

我想要一个具有这样签名的方法:

I want to have a method with a signature like this:

@Transaction
fun deleteAndInsert(): Single<List<Long> > {
    ...
}

推荐答案

我假设您的主要目标是使deleteAndInsert()的返回类型为Single.

I'm assuming your main goal is to have the return type of deleteAndInsert() as Single.

您只需做一些小改动就可以实现

You can achieve that with small modifications

  • 首先使delete()insert()函数同步.
  • 由于@Transaction仅同步工作,因此我们需要创建另一个调用delete()insert()的函数.另外,用@Transaction
  • 注释此功能
  • 创建另一个新函数,该新函数创建一个Single并调用上述函数.
  • first by making delete() and insert() functions synchronous.
  • Since @Transaction only works synchronously, we need to create another function that calls both delete() and insert(). Also, annotate this function with @Transaction
  • Create another new function that creates a Single and calls the above function.
abstract class SampleDao{
    protected abstract fun delete()
    protected abstract fun insert(items: List<Item>) : List<Long>

    @Transaction
    protected open fun deleteAndInsertSync(items: List<Item>): List<Long>{
        delete()
        return insert(items)
    }

    fun deleteAndInsert(items:List<Item>): Single<List<Long>>{
        return Single.create {
            it.onSuccess(deleteAndInsertSync(items))
        }
    }
}

这篇关于如何使用Room Db返回Rx单笔交易?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆