【发布时间】:2017-07-17 08:46:48
【问题描述】:
我的 Android 项目中有以下问题:
我有一个使用 Retrofit 从先前的网络调用中获得的元素列表 (ArrayList)。 CategoryItem 如下所示:
public class CategoryItem {
String id;
String name;
public CategoryItem(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
实际上,这些类别由 20 个元素组成。现在我需要制作一个网络 API 并获取每个类别的产品列表。为此,产品 API 将类别中的 id 作为查询参数。在获得某个类别的产品列表后,我将其添加到内部 SQLite DB 中。
我想用 RxJava(1 和 2)来做这个。
到目前为止,我所做的不是多线程的,而是在 MainThread 上,这是不正确的。 我将在这里添加代码sn-p:
for (int i = 0; i < categoryItems.size(); i++) {
CategoryItem categoryItem = categoryItems.get(i);
final String iCat = categoryItem.getId();
Observable<ProductResponse> call = networkManager.getApiServiceProductsRx().getProductsRx(iCat);
Subscription subscription = call
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ProductResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (e instanceof HttpException) {
HttpException response = (HttpException) e;
int code = response.code();
Log.d("RetrofitTest", "Error code: " + code);
}
}
@Override
public void onNext(ProductResponse response) {
mProductItemsBelongingToACategory = new ArrayList<>();
mProductItemsBelongingToACategory = response.getProductChannel().getProductItems();
mDatabaseHandler.addProducts(iCat, mProductItemsBelongingToACategory);
}
});
subscriptions2.add(subscription);
}
我想用 flatMap 或 flatMapIterable 来做这件事,并最终使用多线程。
【问题讨论】:
标签: android rx-java retrofit2 rx-java2