ObserveOn指定观察者所在线程
Observable
.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
//main
Log.i(TAG, "call: "+Thread.currentThread().getName());
subscriber.onNext("Hello Android !");
}
})
.observeOn(Schedulers.io())//设置观察者运行所在的线程
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
//RxIoScheduler-2
Log.i(TAG, "subscribe call: "+Thread.currentThread().getName());
Log.i(TAG, "subscribe call: "+s);
}
});
上面的代码中Schedulers.io()指定了子线程的类型。除此之外还有很多起来的线程类型。如下表:
SubscribeOn指定被观察者所在线程
//subscribeOn让观察者与被观察者运行在特定子线程中
//Schedulers.computation()和Schedulers.io()都是运行在子线程中
//mainThread android的UI线程
Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
Log.v("haha",Thread.currentThread().getName());
subscriber.onNext("Observable");
}
})//.observeOn(Schedulers.io())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())//运行在主线程中
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.v("haha",Thread.currentThread().getName());
Log.v("haha",s);
}
});