android - 在 doOnComplete android RXJava 之后 LiveData setValue 不起作用
问题描述
我有一个 Completable 可观察对象,并且正在使用 doOnComplete() 运算符来更新我的事件。但是,当我使用setValue
它不工作来更新实时数据时,替换postValue
为对我有用。
任何人都可以帮助我为什么setValue
即使在尝试将调度程序设置为主线程之后也无法工作。
Completable.complete()
.subscribeOn(Schedulers.io())).observeOn(AndriodSchdulers.mainThread())
.delay(getApplication().getResources().getInteger(R.integer.one_minute_time_in_millisec), TimeUnit.MILLISECONDS)
.doOnComplete(() -> liveData.setValue(some value))
.subscribe();
解决方案
我发现了问题,这非常棘手。问题是由delay
操作引起的:
/**
* Delays the emission of the success signal from the current Single by the specified amount.
* An error signal will not be delayed.
*
* Scheduler:
* {@code delay} operates by default on the {@code computation} {@link Scheduler}.
*
* @param time the amount of time the success signal should be delayed for
* @param unit the time unit
* @return the new Single instance
* @since 2.0
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.COMPUTATION)
public final Single delay(long time, TimeUnit unit) {
return delay(time, unit, Schedulers.computation(), false);
}
正如它在文档中所说,默认情况下延迟切换到计算线程。因此,observeOn(AndroidSchedulers.mainThread())
在开始时,您将线程设置为 UI 线程,但随后在链中的延迟操作将其更改回计算线程。因此,解决方法很简单:observeOn
把delay
.
Completable.complete()
.subscribeOn(Schedulers.io())
.delay(1000, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(() -> mutableLiveData.setValue(true));
推荐阅读
- r - 闪亮的反应值更新顺序
- spring - 使用spring hibernate在代码中不重复的想法
- android - 在 facebook android 应用程序上单击我的网站链接给出 net::ERR_NAME_NOT_RESOLVED
- r - 将 content_transformer 与 udpipe_annotate 一起使用
- php - 将生成的二维码图像保存到路径中
- python - 可以隐式检查“零”或“空”的变量的类型
- hadoop - 安装hdp-3.0时找不到与redhat6匹配的操作系统错误
- gmail - Sendmail 和反向 ipv6
- php - 如何在 Yii 中将 URL 的语言更改为单一语言?
- java - WebDriver - 捕获的屏幕截图似乎具有红色或橙色色调