Skip to content Skip to sidebar Skip to footer

Repeat/resubscribe To Observable With Condition Based On Emitted Item(s)

I have enum-values that will be emitted by an Observable: public enum BleGattOperationState { SUCCESSFUL, ERROR, NOT_INITIATED } public Observable

Solution 1:

Use flatMap - the below does not loop infinitely waiting for the expected value. Scroll down for a solution that supports looping.

publicstaticvoidmain(String[] args) {
    Observable<String> o1 = Observable.just("1");
    Observable<String> o2 = Observable.just("2");

    Observable<String> o = System.currentTimeMillis() % 10 < 5 ? o1 : o2; // randomizer

    o.flatMap(s -> {
        if ("1".equals(s)) {
            return o2;
        } else {
            returnObservable.just(s);
        }
    }).subscribe(next -> System.out.println(next));
}

With looping till we get an expected value.

publicstaticvoidmain(String[] args) {
    Observable<String> o = getRandom(); // randomizerresolve(o).subscribe(next -> System.out.println(next));
}

staticObservable<String> resolve(Observable<String> o){
    return o.flatMap(s -> {
        System.out.println("---"+s);
        if ("1".equals(s)) {
            returnresolve(getRandom());
        } else {
            returnObservable.just(s);
        }
    });
}


staticObservable<String> getRandom(){
    Observable<String> o1 = Observable.just("1");
    Observable<String> o2 = Observable.just("2");
    long t = System.currentTimeMillis();
    System.out.println("getRandom: "+(t%10 < 8 ? 1 : 2));
    return t % 10 < 8 ? o1 : o2;
}

Post a Comment for "Repeat/resubscribe To Observable With Condition Based On Emitted Item(s)"