今天我花了很多时间调试为什么即使我已经提到新线程也没有创建。
Observable<DoctorProfileMessage> observable = Observable.defer(
new Callable<ObservableSource<? extends DoctorProfileMessage>>() {
@Override
public ObservableSource<? extends DoctorProfileMessage> call() throws Exception {
return Observable.just(getDummyProfile());
}
});
observable.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread());
observable.subscribe(.....)
当我将代码更改为:
时创建了新线程Observable<DoctorProfileMessage> observable = Observable.defer(
new Callable<ObservableSource<? extends DoctorProfileMessage>>() {
@Override
public ObservableSource<? extends DoctorProfileMessage> call() throws Exception {
return Observable.just(getDummyProfile());
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
我试图理解为什么它在两种情况下都表现不同?
答案 0 :(得分:1)
运算符会返回一个新的Observable
,您应该继续使用它,但是您的第一个代码会应用,然后删除subscribeOn().observeOn()
的结果并订阅原始未经修改的源。
Observable<DoctorProfileMessage> original = Observable.defer(
new Callable<ObservableSource<? extends DoctorProfileMessage>>() {
@Override
public ObservableSource<? extends DoctorProfileMessage> call() throws Exception {
return Observable.just(getDummyProfile());
}
});
Observable<DoctorProfileMessage> withSchedulers =
original.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
original.subscribe(.....); // <------------- chains are immutable in their composition
withSchedulers.subscribe(...);