Observable observable = Observable.from(backToArray(downloadWebPage("URL")))
.map(new Func1<String[], Pair<String[], String[]>>() {
@Override
public Pair<String[], String[]> call(String[] of) {
return new Pair<>(of,
backToArray(downloadWebPage("URL" + of[0])).get(0));
}
});
observable.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(
(new Observer<Pair>() {
@Override
public void onCompleted() {
// Update user interface if needed
}
@Override
public void onError(Throwable t) {
// Update user interface to handle error
}
@Override
public void onNext(Pair p) {
offices.add(new Office((String[]) p.first, (String[]) p.second));
}
}));
这运行,我得到android.os.NetworkOnMainThreadException。我希望它能运行一个由subscribeOn()方法设置的新线程。
答案 0 :(得分:4)
答案 1 :(得分:4)
您可以使用defer()将downloadWebPage
的调用推迟到您订阅可观察对象的时刻。
示例:
private Object slowBlockingMethod() { ... }
public Observable<Object> newMethod() {
return Observable.defer(() -> Observable.just(slowBlockingMethod()));
}
答案 2 :(得分:0)
你应该从
改变**observable.subscribeOn(Schedulers.newThread())**
到
**observable.subscribeOn(Schedulers.io())**