在doOnComplete android RXJava之后LiveData setValue不起作用

时间:2018-11-29 21:09:15

标签: android rx-java2 scheduler android-livedata

我有一个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();

1 个答案:

答案 0 :(得分:3)

我发现了问题,这非常棘手。问题是由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