【问题标题】:Use blockingGet() on Maybe that already observes on AndroidSchedulers.mainThread()在可能已经在 AndroidSchedulers.mainThread() 上观察到的情况下使用 blockingGet()
【发布时间】:2019-10-10 08:47:07
【问题描述】:

我的应用程序的 Room 数据库包裹在一个 RxJava2 数据访问层中,该层修改所有 Singles、Maybes 等以订阅 Schedulers.io() 调度程序,并观察 AndroidSchedulers .mainThread() 调度程序。

这被认为是一个好主意,因为如果您尝试从主线程之外修改 UI,Android 有时会出现异常行为,这是完成查询后的典型行为。

public <T> Maybe<T> flow(Maybe maybe) {
    return maybe
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}

我现在有一部分应用程序需要从数据库中同步检索元素。我的设计没有预料到这一点。当我执行#blockingGet() 时,我遇到了死锁,我在this one 等其他问题中读到过。

在我需要同步检索一些数据的边缘情况下,有什么方法可以修改流以不实际观察主线程?还是我必须完全重新评估这个设计,让每个单独的调用决定使用哪个调度器来观察?

--

在我的 Activity 中,与 UI 元素交互时:

Book book = mBooksDataSource.getBookWithId(1L)
    .observeOn(Schedulers.io())
    .blockingGet();
Log.d(LOG_TAG, "I am here."); //Never reached

在数据源中:

public Maybe<Book> getBookWithId(long bookId) {
    return mReservoir.flow(mBooksDao.getBookWithId(bookId));
    //The reservoir is the class containing the flow method from further above.
}

在书道中:

@Transaction @Query("SELECT ...")
public abstract Maybe<Book> getBookWithId(long bookId);

【问题讨论】:

  • 您是否尝试过使用单独的调度程序设置另一个observeOn()? (即flow(...).observeOn(io())
  • 我有,不幸的是我仍然遇到同样的行为......
  • 这很奇怪 - observeOn() 下面的所有内容都应该在指定的调度程序上执行。您能否在您的问题中添加更多代码以显示您如何使用此方法,或任何其他可能有助于诊断的代码?
  • @PPartisan 我添加了更多代码。这个应用程序来自我的工作,所以我无法粘贴整个课程。如果您认为这会进一步澄清,我可以在 GitHub 中创建一个示例应用程序。谢谢。
  • 您确定Book book = mBooks...blockingGet(); 行是从工作线程调用的吗? blockingGet() 将阻塞当前线程,而不管流中使用的调度程序。即使您完全删除flow() 调用,问题仍然存在。

标签: android rx-java2 rx-android


【解决方案1】:

我认为 Sanlok Lee 的评论是正确的,您在主线程上调用 blockingGet()。这是忽略调度程序。因此,您可以使用ExecutorService,或尝试以下操作:

Schedulers.io().scheduleDirect(() -> {
    final Book book = mBooksDataSource.getBookWithId(1L).blockingGet();
    //Do something with the book
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-28
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多