android - 房间线程,RxJava,选择问题
问题描述
我对 Room 和 Rx 可完成有一个奇怪的问题。不过很容易复制。问题来自线程,但不明白为什么..
当我订阅 Rx 可完成并等待插入成功时,结果表上的下一个选择(选择最大值或计数)在使用另一个线程时不起作用。
val entryTable = TestDbUtil.createEntryTable(
entry.id, // 1
entryTableFieldId, // 1
rowIndexExpected // row index: 123
)
// Insert a row in entry table object with entry.id = 1 and field.id = 1 and row index is 1234
// The insert is a Completable, we subscribe to it to get the result insertion
// When insert is success, we are looking to get the max row index from it.
entryTableDao.insert(entryTable).subscribe({
Executors.newSingleThreadExecutor().execute { // With thread I have an error here!! Without this line it's working fine
val max = entryTableDao.findMaxRowIndex(entry.id, entryTable.fieldId)
Assert.assertEquals(rowIndexExpected, max) // Always 0 but should be 123
}
},
{ error ->
Assert.assertNull(error)
}
...
我尝试了多种方法,比如到处都是 rx,但我遇到了同样的问题。这可能是与交易有关的问题?
编辑
有了评论,我可以像说的那样做,doOnComplete 和使用 Schedulers.from(executor).. 这对我的 TU 有用,但在我的应用程序中没有任何工作..
这里的代码:
fun getMaxIndex(entryId: String, fieldId: Int): LiveData<Int> {
val result = MutableLiveData<Int>()
entryTableDao.findMaxRowIndex(entryId, fieldId)
.subscribeOn(Schedulers.single())
.observeOn(AndroidSchedulers.mainThread())
.doOnSuccess {
// Never called even if there are some data in db...
result.value = it
}
.doOnError {
// Not called.
result.value = 0
}
.doOnComplete {
// Always called, obviously, but I don't have the onSuccess.
result.value = 0
}
.subscribe()
return result
}
问题:
- 如何在我的 TU 中测试这种行为?就像observeOn主线程一样,因为我无法重现它。
- 在第二个代码片段中,subscribe {result ->} 和 doOnSuccess { result -> } 有什么区别
- 在第二个代码片段中,为什么我没有任何响应数据?我花了这么多时间在这个问题上......我无法弄清楚......
TU 在插入结果成功后调用 findMaxRowIndex,在我的应用程序中它是相同的行为,即使代码没有显示它。
解决方案
正如评论中所讨论的那样,与 doOnComplete 的组合足以满足您的需要。Completable 有 onComplete 和 onError,所以如果你需要在这之后做一些事情,你可以使用 doOnComplete。
下面是 Completable 的官方文档:Completable: doOnComplete
如果你需要在后台线程上做事情,你应该使用 RxJava subscribeOn。更多信息:了解 RxJava subscribeOn 和 observeOn。如果您想使用 Executor,您仍然可以通过
Schedulers.from(Executor 执行者)
推荐阅读
- python - Numpy:获取对应数组具有特定值的数组行导致IndexError:布尔索引与索引数组不匹配
- python - 如何在python中使用pdfminer从在线PDF中提取文本
- c# - 如何设置 http 标头以便在 ASP.NET Core 中不发生缓存?
- sql - 使用“parititon by”和窗口函数在postgres中返回多于一行?
- python - 使用 glob 排除子文件夹
- postgresql - Postgres 在“A OR exists(B)”查询中进行优化
- csv - 如何在 GoogleShell 中使用 gsutil compose 并跳过第一行?
- javascript - Shopify - 购买免费产品
- javascript - 将 Azure Cosmos 表值转换为 HTML
- voltdb - 如何限制voltdb使用的内存