Skip to content Skip to sidebar Skip to footer

Rx Java Observable Execute Until Some Condition

I am trying to find a way to execute observable until some condition is met. Consider the following example: myDelayedObservable = createListenerObserver(); public Observable&

Solution 1:

1) You need to map all observables to the same type, eg. Observable<Boolean>, so you can merge them:

observable1.map(String s ->"...".equals(s))
observable2.map(Integer i -> i > 0 && i < 100)
observable3.map(MyClass m ->true)
...

2) Use Observable.merge() to merge them all into single stream. Using zip for this purpose will only work if all observables emit the same number of items, otherwise it will complete as soon as the first one completes, without waiting for the rest.

Observable<Boolean> allInOne = Observable.merge(observable1, observable2, ...);

3) myDelayedObservable is just one of those observables that shall hold allInOne incomplete until some listener calls back. Use Subject for this purpose:

Subject<Boolean> myDelayedObservable = PublishSubject.create();

4) When your listener is ready, call myDelayedObservable.onComplete().

5) Subscribe to allInOne and react on completion:

allInOne.subscribe(b -> { ... }, e -> { ... },
    () -> { ... goaheadwithyournexttask ... });

Solution 2:

Try with:

PublishSubject<Boolean> myDelayedObservable = PublishSubject.create<>();

or for RxJava2

 PublishProcessor<Boolean> myDelayedObservable = PublishProcessor.create<>();

And when ready just call

 myDelayedObservable.onNext(true)
 //not this, myDelayedObservable.onComplete();

Post a Comment for "Rx Java Observable Execute Until Some Condition"