android - 在 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 中执行链接和组合?
解决方案
您必须为此使用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())
}
推荐阅读
- qt - qt中带有复选框的文件系统树视图
- c# - 使用 C# 和 Firebase 的聊天应用程序 android 本机
- reactjs - 如何在 VS Code Mac 上保存代码?
- javascript - 使用 fetch API 在 React 中过滤掉 API 响应中的字段
- c - Scanf 导致分段错误 - 输入时间
- python - 使用 pysftp 下载大文件
- python - pandas to_hdf() 函数中 complevel 参数的作用是什么?
- f# - 我能知道 Xunit 中失败的实际表达式吗?
- java - 将对象/数组从 JSON 解析为 Java
- python - 为什么我在 Win 10 中使用 pip 时出现 Traceback 错误?