我有一个Completable观察对象,并且正在使用doOnComplete()运算符更新事件。但是,当我使用setValue
更新livedata时,用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));
You can also checkout this medium post about it
关于android - 在doOnComplete android RXJava之后LiveData setValue不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53547625/