Believe that the small partners in the use of Rxjava and retrofit request network, have encountered such a scenario, in the IO thread request network parsing data, and then return to the main thread SetData, update view attempt, then also certainly familiar with the following lines of code:
.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber);
If the number of network requests is relatively small, as a sloppy (lazy cancer) in the two youth can reluctantly accept the copy and paste the above switch schedulers code, but if the number of Biz request network more up, and do not want to break the ring RX chain structure, then how to do? In fact, using the compose operator to write a single line of code at a time to complete the work thread switch!
First look at the final effect:
RetrofitClient.singletonDemoService("http://gank.io/api/random/data/").requestNet("福利","1").compose(schedulersTransformer()).subscribe(subscriber);
.compose(schedulersTransformer())
thread switching is done with just one line of code.
The principle of the compose operator is simple and verbose:
Unlike maps, Flatmap, and other lift operations, the events and sequences released by observable are changed, The compose operator operates directly on the current observable (it can be simply understood as a constant. Method name (). Method name () chain Operation current observable), so we can naturally add the operation of switching threads here.
So let's do it ~
-
1. First compose () needs to pass in a parameter of type Observable.transformer, then we can do it directly in this new one;
-
2. In the above transformer object, By rewriting the call method, we can get a observable object and perform a series of lift transformations (which can naturally switch threads);
observable. Transformer Schedulerstransformer () {return new observable. Transformer () {@override public Object call (object observable) {return ((observable) observable). subscribeon (schedulers.io ()). Unsubscribeon (schedulers.io ()). Observeon (androidschedulers.mainthread ());}; }
observable.compose (schedulersTransformer()).subscribe(subscriber)
Android uses Rxjava compose operator to eliminate duplicate code