首页 > 解决方案 > 房间线程,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
}

问题:

  1. 如何在我的 TU 中测试这种行为?就像observeOn主线程一样,因为我无法重现它。
  2. 在第二个代码片段中,subscribe {result ->} 和 doOnSuccess { result -> } 有什么区别
  3. 在第二个代码片段中,为什么我没有任何响应数据?我花了这么多时间在这个问题上......我无法弄清楚......

TU 在插入结果成功后调用 findMaxRowIndex,在我的应用程序中它是相同的行为,即使代码没有显示它。

标签: androidmultithreadingkotlinandroid-room

解决方案


正如评论中所讨论的那样,与 doOnComplete 的组合足以满足您的需要。Completable 有 onComplete 和 onError,所以如果你需要在这之后做一些事情,你可以使用 doOnComplete。
下面是 Completable 的官方文档:Completable: doOnComplete
如果你需要在后台线程上做事情,你应该使用 RxJava subscribeOn。更多信息:了解 RxJava subscribeOn 和 observeOn。如果您想使用 Executor,您仍然可以通过

Schedulers.from(Executor 执行者)


推荐阅读