如何基于RxJava2的条件执行并行处理

时间:2018-05-21 12:19:56

标签: android parallel-processing rx-java2

我正在尝试在我当前的Android项目中使用RxJava2。

position: relative

我有许多遵循这种模式的用例。

   implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
   implementation 'io.reactivex.rxjava2:rxjava:2.1.12'

一个这样的用例是我检查我的本地数据库是否需要从远程源刷新。

我已经走到这一步了,现在我被卡住了......

1). Check a condition is true or false.
2). When condition is true
2.1). Execute multiple processes in parallel
2.2). wait until all parallel process have completed.
3). When condition is false.
3.1). Do nothing.

有问题的方法类似于: -

 refreshRequired().subscribeOn(Schedulers.io()).subscribe(getObserver());

我无法理解的是当/** * * @return */ private Single<Boolean> refreshRequired() { return Single.create(new SingleOnSubscribe<Boolean>() { @Override public void subscribe(final SingleEmitter<Boolean> emitter) { if (emitter.isDisposed()) { } else { emitter.onSuccess(isRefreshRequired()); } } }); } /** * * @return */ private SingleObserver<Boolean> getObserver() { return new SingleObserver<Boolean>() { @Override public void onSubscribe(final Disposable disposable) { } @Override public void onSuccess(final Boolean value) { Log.d(TAG, "onSuccess() called with: value = [" + value + "]"); } @Override public void onError(final Throwable throwable) { Log.e(TAG, "onError() called with: ", throwable); } }; } 方法获得public void onSuccess(final Boolean value) {}

值时,如何触发并行处理

此过程的伪代码为: -

true

1 个答案:

答案 0 :(得分:2)

您可以通过使用filter运算符将反应流分成两部分来实现这一目的:

Observable<Boolean> refreshRequiredObservable = refreshRequired();

refreshRequiredObservable.filter(refreshRequired -> refreshRequired)
        .doOnNext(aBoolean -> System.out.println("Do first thing"))
        .doOnNext(aBoolean -> System.out.println("Do second thing"))
        .doOnNext(aBoolean -> System.out.println("Do third thing"))
        .subscribe();

refreshRequiredObservable.filter(refreshRequired -> !refreshRequired)
        .doOnNext(aBoolean -> System.out.println("Do nothing"))
        .subscribe();