首页 > 解决方案 > 在 Android 中链接和组合 RXJava 调用

问题描述

我有一个使用 Room 执行加载操作的应用程序。

它调用以下查询:

select * from reports r join brands b on r.brandId = b.id join models m on r.modelId = m.id join results s on s.reportId = r.id where r.id = :id

当提供一个 id 时,这会返回一个 Single<FullReportEntity>

这可以按预期工作,但我必须拆分调用并将它们链接起来以从(可能)不同的数据源中获取结果。

我要使用的命令是:

fun getReportById(id:UUID): Single<ReportEntity>

fun getBrandById(id:UUID): Single<BrandEntity>

fun getModelById(id:UUID): Single<ModelEntity>

fun getResultsForReport(reportId:UUID) : Single<List<ReportEntity>>

使用协程(在将上述函数更改为暂停的函数之后)我可能会做这样的事情

GlobalScope.launch(dispatchers.UI) {
    val report = async(dispatchers.IO) { ds.getReportById(id) }
    val brand = async(dispatchers.IO) { ds.getBrandById(report.await().id) }
    val model = async(dispatchers.IO) { ds.getModelById(report.await().id) }
    val results = async(dispatchers.IO) { ds.getResulstsForReport(report.await().id) }
    fullReport = withContext(dispatchers.CPU) {
       FullReportEntity(report.await(), brand.await(), model.await(),results.await)
    }
}

但我必须在 RxJava 中执行上述操作,我仍在学习,所以我的问题是如何在 RxJava 中执行链接和组合?

标签: androidkotlinrx-java2

解决方案


您必须为此使用zip功能。它会是这样的:

ds.getReportById(id)
    .flatMap { report ->
        Single.zip(
            ds.getBrandById(report.id),
            ds.getModelById(report.id),
            ds.getResultsForReport(report.id),
            Function3<BrandEntity, ModelEntity, List<ReportEntity>, FullReportEntity> { brand, model, results ->
                FullReportEntity(report, brand, model, results)
            }
        ).subscribeOn(Schedulers.computation())
    }

推荐阅读