我想在我的项目中使用RxAndroid, 我让线程睡了50ms 但它导致了一个代码
public void getTypeAndCommodity() {
Observable.from(getCommodities())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Commodity>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Commodity commodity) {
}
});
}
和getCommodities:
private ArrayList<Commodity> getCommodities() {
// some test info
ArrayList<Commodity> list = new ArrayList<>();
for (int i = 0; i < 99; i++) {
Commodity commodity = new Commodity();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
commodity.setName("name" + i);
commodity.setType("type" + (i + 1) / 10);
list.add(commodity);
}
return list;
}
为什么它会导致问题?请帮忙
答案 0 :(得分:0)
这是因为getCommodities()在主线程中执行,并且只有emit的项目在io线程中使用subscribeOn(Schedulers.io())执行。如果你想在后台线程中执行getCommidities(),你需要使用defer()方法创建一个observable:
Observable.defer(new Func0<Observable<Object>>() {
@Override public Observable<Object> call() {
return Observable.from(getCommodities());
}
}).subscribeOn(Schedulers.io())...
如果您需要更多信息:http://blog.danlew.net/2015/07/23/deferring-observable-code-until-subscription-in-rxjava/