介绍一下业务逻辑:获取接口数据,根据接口内容判断是否需要继续获取数据。
本文使用递归思路,通过RxJava来实现此功能,获取数据的Observable直接用模拟的Observable.just()替代。关键点使用concatMap
和concatWith
操作符
代码块
public Observable<Integer> getInt(int i) {
return Observable.just(i).concatMap(integer -> {
if (integer == 10) { //判断条件
return Observable.just(10); //发射数据
} else {
return Observable
.just(integer)
.concatWith(getInt(integer + 1));
//连接发射
}
});
}
public void testMain() {
getInt(0).subscribe(getSubscriber());
}
private Subscriber<Object> getSubscriber() {
return new Subscriber<Object>() {
@Override
public void onCompleted() {
LogUtils.d("onCompleted");
}
@Override
public void onError(Throwable e) {
LogUtils.d("onError : " + e.toString());
}
@Override
public void onNext(Object o) {
LogUtils.d("onNext : " + o);
}
};
}
输出结果
01-05 10:42:13.257 24959-24975/? D/LogUtils: onNext : 0
01-05 10:42:13.257 24959-24975/? D/LogUtils: onNext : 1
01-05 10:42:13.257 24959-24975/? D/LogUtils: onNext : 2
01-05 10:42:13.257 24959-24975/? D/LogUtils: onNext : 3
01-05 10:42:13.257 24959-24975/? D/LogUtils: onNext : 4
01-05 10:42:13.258 24959-24975/? D/LogUtils: onNext : 5
01-05 10:42:13.258 24959-24975/? D/LogUtils: onNext : 6
01-05 10:42:13.258 24959-24975/? D/LogUtils: onNext : 7
01-05 10:42:13.258 24959-24975/? D/LogUtils: onNext : 8
01-05 10:42:13.258 24959-24975/? D/LogUtils: onNext : 9
01-05 10:42:13.258 24959-24975/? D/LogUtils: onNext : 10
01-05 10:42:13.258 24959-24975/? D/LogUtils: onCompleted