首页 > 解决方案 > 在 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();

标签: androidrx-java2schedulerandroid-livedata

解决方案


我发现了问题,这非常棘手。问题是由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 线程,但随后在链中的延迟操作将其更改回计算线程。因此,解决方法很简单:observeOndelay.

Completable.complete()
    .subscribeOn(Schedulers.io())
    .delay(1000, TimeUnit.MILLISECONDS)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(() -> mutableLiveData.setValue(true));

你也可以查看这篇关于它的媒体帖子


推荐阅读