我有一个奇怪的问题和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和使用调度程序。
在这里代码:
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中测试这种行为?就像观察主线程一样,因为我无法复制它。
- 在第二个代码段中,订阅{结果 ->}和doonSuccess {result->} 之间有什么区别
- 在第二个代码段中,为什么我没有任何响应数据?我在这个问题上花了很多时间...我无法弄清楚...
tu调用insert结果后的FindMaxrowIndex,在我的应用程序中,即使代码未显示。
如评论中所讨论的,与dooncomplete的组合足以满足您的需求。可完整的内容有启动和ONERROR,因此,如果您需要做一些事情,则可以使用DoonComplete。
以下是可完整的官方文件:可完整:dooncomplete
如果您需要在背景线程上进行操作,则应使用RXJAVA订阅。更多这里:了解RXJAVA订阅和观察。如果您想使用遗嘱执行人,您仍然可以通过
schedulers.from(executor execor)