RxJava等待布尔值(条件)

时间:2016-10-28 16:56:09

标签: java rx-java

方法updateFromRemote()

public class WorkshiftSettingsDaoImpl implements WorkshiftSettingsDao {

    private boolean isUpdating = false;

    public Observable<WorkshiftSettings> updateFromRemote() {
        return remoteDataStore.get()
                .retryWhen(RxOperatorsHelpers::retryWhenAnyIoExceptionWithDelay)
                .doOnSubscribe(this::setUpdatingStarted)
                .doOnUnsubscribe(this::setUpdatingFinished)
                .flatMap(workshiftSettings -> localDataStore.put(workshiftSettings));
    }

    private void setUpdatingStarted() {
        if(isUpdating) throw new RuntimeException("already updating");
        isUpdating = true;
    }

    private void setUpdatingFinished() {
        if(!isUpdating) throw new RuntimeException("already finished");
        isUpdating = false;
    }

}

如何实现此行为:

如果isUpdating == true然后等到它将更改为false并执行显示链。

if isUpdating == false然后只执行显示的链。

有我的解决方案:

public Observable<WorkshiftSettings> updateFromRemote() {
    Observable<WorkshiftSettings> updateRemoveDataObservable =  remoteDataStore.get()
            .retryWhen(RxOperatorsHelpers::retryWhenAnyIoExceptionWithDelay)
            .doOnSubscribe(this::setUpdatingStarted)
            .doOnUnsubscribe(this::setUpdatingFinished)
            .flatMap(workshiftSettings -> localDataStore.put(workshiftSettings));

    return Observable.fromCallable(() -> {
        while (isUpdating) {
            Thread.sleep(1000);
        }
        return null;
    }).concatMap(o -> updateRemoveDataObservable);
}

但我觉得有问题:)

有更好的主意吗?

1 个答案:

答案 0 :(得分:3)

不确定,我的流程是否正确无误。但我想你有一些&#34;地点&#34;其中isUpdating已更改。 如果是,您可以创建 final BehaviorSubject<Boolean> isUpdatingSubject = BehaviorSubject.<Boolean>create() 在这个&#34; place&#34 ;,而不是改变布尔变量,你做:  isUpdatingSubject.onNext(false)

并且

public Observable<WorkshiftSettings> updateFromRemote() {
    return isUpdatingSubject
            .distinctUntilChanged()
            .filter(new Func1<Boolean, Boolean>() {
                @Override
                public Boolean call(BookingErrorActivity isUpdating) {
                    return !isUpdating;
                }
            })
            .flatMap(new Func1<Object, Observable<WorkshiftSettings>>() {
                @Override
                public Observable<WorkshiftSettings> call(Object o) {
                    return remoteDataStore.get()
                            .retryWhen(RxOperatorsHelpers::retryWhenAnyIoExceptionWithDelay)
                            .doOnSubscribe(this::setUpdatingStarted)
                            .doOnUnsubscribe(this::setUpdatingFinished)
                            .flatMap(workshiftSettings -> localDataStore.put(workshiftSettings));
                }
            });

}

但是要小心:有了这样的解决方案,当isUpdatingSubject发出true时,这个Observable每次都会发出,所以有时它可能并不酷。 为防止这种情况发生,您可以在.first()

之前使用flatMap()

PS 您可以阅读有关BehaviorSubject

的更多信息

PSS 抱歉,我习惯使用java7语法