RxJava線程控制

 RxJava中的線程轉換主要經過下面兩個方法:app

1.subscribeOnspa

2.observeOn線程

1、subscribeOncode

1.調用一次subscribeOn時:server

Observable observable;
Schedulers schedulers;
Observer observer;
observable.subscribeOn(schedulers).subscribe(observer)

經過解析源碼可轉化爲:blog

observer.onSubscribe();
schedulers線程{
       observable.subscribe(observer)
}

在原線程調用observer的onSubscribe 方法,並在schedulers的線程中調用observable 的subscribe 方法。源碼

 

2.當屢次調用subscribeOn時:io

Observable observable;
Schedulers schedulers1;
Schedulers schedulers2;
Observer observer;
observable.subscribeOn(schedulers1)
     .subscribeOn(schedulers2)
     .subscribe(observer)

可轉化爲:function

observer.onSubscribe();
schedulers2線程{
     schedulers1線程{
       observable.subscribe(observer)
     }
}

因此subscribOn只有第一次有效。class

2、observeOn

1.調用一次observeOn

Observable observable;
Schedulers schedulers;
Observer observer;
observable.observeOn(schedulers).subscribe(observer)

可轉化爲:

observer.onSubscribe();
schedulers線程{
       observer.next()
       observer.complete()
}

 

當屢次調用observeOn時:

Observable observable;
Schedulers schedulers1;
Schedulers schedulers2;
Observer observer;
observable.observeOn(schedulers1)
        .observeOn(schedulers2)
        .subscribe(observer)

可轉化爲:

observer.onSubscribe();
schedulers1線程{
     schedulers2線程{
          observer.next()
          observer.complete()
     }
}

 

當時用map操做符時:

observable.map()
     .observeOn(schedulers1)
     .map(function)
     .observeOn(schedulers2)
     .subscribe(observer)

可轉化爲:

observer.onSubscribe();
schedulers1線程{
    function.apply()
     schedulers2線程{
          observer.next()
          observer.complete()
     }
}
相關文章
相關標籤/搜索