RxJava线程控制

 RxJava中的线程转换主要通过下面两个方法:

1.subscribeOn

2.observeOn

一、subscribeOn

1.调用一次subscribeOn时:

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

通过解析源码可转化为:

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

在原线程调用observer的onSubscribe 方法,并在schedulers的线程中调用observable 的subscribe 方法。

 

2.当多次调用subscribeOn时:

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

可转化为:

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

所以subscribOn只有第一次有效。

二、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()
     }
}

 

posted @ 2016-07-31 10:36  maozs  阅读(1105)  评论(0编辑  收藏  举报