如何使用反应式 android 和改造发出多个请求 [英] How to make multiple requests with reactive android and retrofit
问题描述
我有调用 getShops() 方法的演示者.
I have presenter which calls getShops() method.
Observable<List<Shop>> observable = interactor.getData();
Subscription subscription = observable
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<Shop>>() {
@Override
public void onCompleted() {
view.hideProgress();
}
@Override
public void onError(Throwable e) {
super.onError(e);
view.hideProgress();
}
@Override
public void onNext(List<Shop> shops) {
handleShops(shops);
view.onSuccess();
}
});
composite.add(subscription);
在数据层中,我有 Interactor,它通过 Retrofit 向服务器发出请求并返回 List
.
In data layer I have Interactor which makes request to server with Retrofit and return List<Shop>
.
@Override
public Observable<List<Shop>> getData() {
return api.getShops(pageNum).map(new Func1<ShopWrapper, List<Shop>>() {
@Override
public List<Shop> call(ShopWrapper wrapper) {
return wrapper.getShops();
}
});
}
问题是我需要用不同的页面参数发出多个相同的请求,因为服务器每页返回N家商店,我需要收集所有商店然后返回Observable
>代码>给演示者.
The problem is that I need to make multiple identical requests with different page parameter, because server returns N shops per page, and I need collect all shops and then return the Observable<List<Shop>>
to presenter.
我是响应式编程的新手,也许有一些运算符可以做到这一点.
I'm new to Reactive programming, maybe there is some operator which allows to do this.
任何帮助将不胜感激.
推荐答案
只需使用 Observable.range
和 concatMap
调用即可.如果你不知道你的上限,你可以在某些条件下使用 takeUntil
.
Just use Observable.range
and concatMap
your calls with it.
If you don't know your upper range, you can use takeUntil
with some condition.
像这样:
Observable.range(0, Integer.MAX_VALUE)
.concatMap(pageNum -> api.getShops(pageNum).map(doYourMapping))
.takeUntil(shops -> someCondition);
如果你只想要一个 onNext 调用,你可以在 takeUntil 之后添加:
If you want only one onNext call you can add this after takeUntil:
.flatMapIterable(shops -> shops)
.toList();
这篇关于如何使用反应式 android 和改造发出多个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!