当前位置: 代码迷 >> 综合 >> RxJava 1.0版本入门篇之--4
  详细解决方案

RxJava 1.0版本入门篇之--4

热度:103   发布时间:2023-10-08 23:27:08.0

ObserveOn指定观察者所在线程

 Observable.create(new Observable.OnSubscribe<String>() {@Overridepublic void call(Subscriber<? super String> subscriber) {//mainLog.i(TAG, "call: "+Thread.currentThread().getName());subscriber.onNext("Hello Android !");}}).observeOn(Schedulers.io())//设置观察者运行所在的线程.subscribe(new Action1<String>() {@Overridepublic void call(String s) {//RxIoScheduler-2Log.i(TAG, "subscribe call: "+Thread.currentThread().getName());Log.i(TAG, "subscribe call: "+s);}});

上面的代码中Schedulers.io()指定了子线程的类型。除此之外还有很多起来的线程类型。如下表:

RxJava 1.0版本入门篇之--4

SubscribeOn指定被观察者所在线程

    //subscribeOn让观察者与被观察者运行在特定子线程中//Schedulers.computation()和Schedulers.io()都是运行在子线程中//mainThread android的UI线程Observable.create(new Observable.OnSubscribe<String>() {@Overridepublic 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>() {@Overridepublic void call(String s) {Log.v("haha",Thread.currentThread().getName());Log.v("haha",s);}});