Christopher
Christopher

Reputation: 10259

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<BleGattOperationState> readRssi() {
  return Observable.<BleGattOperationState>create(subscriber -> {
    if (someCondition()) {
        subscriber.onNext(BleGattOperationState.SUCCESSFUL);
    } else {
        subscriber.onNext(BleGattOperationState.NOT_INITIATED);
    }
  });
}

Is there a way to resubscribe or to repeat the observable, if the NOT_INITIATED value is emitted? Basically something like:

readRssi()
    .repeatIf(state -> state == NOT_INITIATED)
    .subscribe();

I know the operators repeatWhen, which does not allow evaluation of the emitted items and retryWhen, which only acts if an error is emitted.

Upvotes: 3

Views: 1408

Answers (1)

Pavan Kumar
Pavan Kumar

Reputation: 4800

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

public static void main(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 {
            return Observable.just(s);
        }
    }).subscribe(next -> System.out.println(next));
}

With looping till we get an expected value.

public static void main(String[] args) {
    Observable<String> o = getRandom(); // randomizer
    resolve(o).subscribe(next -> System.out.println(next));
}

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


static Observable<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;
}

Upvotes: 2

Related Questions