使用基于发出项目的条件重复/重新订阅Observable

时间:2017-01-09 10:38:56

标签: android rx-java

我有enum - 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);
    }
  });
}

如果发出NOT_INITIATED值,有没有办法重新订阅或重复观察?基本上是这样的:

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

我知道运算符repeatWhen,它不允许评估发出的项目和retryWhen,只有在发出错误时才会起作用。

1 个答案:

答案 0 :(得分:1)

使用flatMap - 以下不会无限循环等待预期值。向下滚动以寻找支持循环的解决方案。

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));
}

循环直到我们得到预期值。

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