Rxjava is now a very avant-garde asynchronous framework, but also because he is very new, so it is more difficult to navigate.
Just like Okhttp calls its Cancel method directly in OnStop or OnDestroy, but Rxjava is not that simple.
Because if each request get observable object, and then OnStop in unsubscribe Cancel, this is not conducive to encapsulation. And it will cause a lot of code, so I found a solution with rxlifecycle.
Pilot Pack
‘com.trello:rxlifecycle:0.5.0‘ ‘com.trello:rxlifecycle-components:0.5.0‘
Then write rxactivity, the original author GitHub on the source code, I based on my own situation slightly modified a bit.
ImportAndroid.os.Bundle;ImportAndroid.support.annotation.CallSuper;ImportAndroid.support.annotation.NonNull;Importandroid.support.v4.app.FragmentActivity;ImportCom.trello.rxlifecycle.ActivityEvent;ImportCom.trello.rxlifecycle.ActivityLifecycleProvider;ImportCom.trello.rxlifecycle.RxLifecycle;ImportRx. Observable;ImportRx.subjects.BehaviorSubject;/** * Created by a on 2016/5/6. * * Public class rxactivity extends fragmentactivity implements Activitylifecycleprovider { Public Finalbehaviorsubject<activityevent> lifecyclesubject = Behaviorsubject.create ();@NonNull @Override PublicObservable<activityevent>Lifecycle() {returnLifecyclesubject.asobservable (); }@NonNull @Override Public<T> Observable.transformer<t, t>binduntilevent(@NonNull activityevent event) {returnRxlifecycle.binduntilevent (Lifecyclesubject, event); }@NonNull @Override Public<T> Observable.transformer<t, t>bindtolifecycle() {returnRxlifecycle.bindactivity (Lifecyclesubject); }@Override @CallSuper protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Lifecyclesubject.onnext (activityevent.create); }@Override @CallSuper protected void OnStart() {Super. OnStart (); Lifecyclesubject.onnext (Activityevent.start); }@Override @CallSuper protected void Onresume() {Super. Onresume (); Lifecyclesubject.onnext (Activityevent.resume); }@Override @CallSuper protected void OnPause() {lifecyclesubject.onnext (activityevent.pause);Super. OnPause (); }@Override @CallSuper protected void OnStop() {lifecyclesubject.onnext (activityevent.stop);Super. OnStop (); }@Override @CallSuper protected void OnDestroy() {lifecyclesubject.onnext (Activityevent.destroy);Super. OnDestroy (); }}
Inherit the rxactivity with your own activity.
Add to the location of the networking request
. Compose (Rxlifecycle.binduntilevent (Lifecycle (), activityevent.stop))
This means canceling the request at the stop cycle.
I used the previous blog upload Image example, now is mainactivity into secondactivity, click the button after uploading a picture, and then get the results returned.
File File =NewFile (environment.getexternalstoragedirectory () +"/123.png"); Httputil.getiimagepp (). Uploadimage ("C1a2b3ab56a2f218aed9b2ab3c16ce88","be8318b73cef1c2bcafb6c8a77922436", Httputil.postfileparams ("img", file))//encapsulates the main thread subscribe running in a sub-thread, the following will tell how to encapsulate. . Compose (Rxhelper.io_main (secondactivity. This))//.compose (Rxlifecycle.binduntilevent (Lifecycle (), activityevent.stop)). Subscribe (NewRxsubscriber<object> () {@Override Public void _onnext(Object o) {L.E ("AAAA"); Tv.settext (String) o); }@Override Public void _OnError(String msg) { } });
Without adding. Compose (rxlifecycle.binduntilevent (Lifecycle (), activityevent.stop), click the button to upload and immediately return to the log log of the previous activity:
After returning to Mainactivity, about 2 seconds later, this sentence appears.
05-0618:37:58.59015642-15642/com.sanniuben.myapplication E/way: aaaa
After the addition, there was no return.
It can be seen that he canceled the request at the time of OnStop.
Rxlifecycle author of GitHub
Rxfragment Source page
The fragment operation is similar to this. Just need to inherit rxfragment
Next is the encapsulation.
Public class rxhelper { //Sub-thread run, main thread callback Public Static<T> Observable.transformer<t, t>Io_main(FinalRxactivity context) {return NewObservable.transformer<t, t> () {@Override PublicObservable<t>Pager(observable<t> tobservable) {return(observable<t>) tobservable. Subscribeon (Schedulers.io ()). Doonsubscri Be (NewAction0 () {@Override Public void Pager() {//Per request main thread Display dialog boxProgressdialogutil.showprogress (Context,"Loading, please wait"); }}). Subscribeon (Androidschedulers.mainthread ()). OB Serveon (Androidschedulers.mainthread ()). Compose (Rxlifecycle.binduntilevent (Context.lifecycle (), Ac Tivityevent.stop)); } }; }}
Subscriber
/** * Created by a on 2016/5/6. * * Public Abstract classRxsubscriber<t> extends subscriber<t>{@Override Public void oncompleted() {//Cancel the dialog box when finishedProgressdialogutil.dismiss (); } @Override Public void OnError(Throwable e) {E.printstacktrace (); _OnError (E.getmessage ());if(! Netutils.isconnected (Myapplication.getcontextobject ())) {Toast.maketext (Myapplication.getcontextobject ()),"The request failed, please check the network!", Toast.length_short). Show (); Progressdialogutil.dismiss ();return; }} @Override Public void OnNext(T T) {_onnext (t); } Public Abstract void_OnNext(T T); Public Abstract void_OnError(String msg);}
Now take a look at the new request
File File =NewFile (environment.getexternalstoragedirectory () +"/123.png"); Httputil.getiimagepp (). Uploadimage ("C1a2b3ab56a2f218aed9b2ab3c16ce88","be8318b73cef1c2bcafb6c8a77922436", Httputil.postfileparams ("img", file))//Just add this sentence. Compose (Rxhelper.io_main (secondactivity. This))//Here is new's our own Rxsubscriber. Subscribe (NewRxsubscriber<object> () {@Override Public void _onnext(Object o) {L.E ("AAAA"); Tv.settext (String) o); }@Override Public void _OnError(String msg) { } });
This completes the encapsulation of the Rxjava. Now, every time you access the network, the dialog box is displayed, and the cancel dialog is requested, and the request is canceled at the activity lifecycle stop.
about how to achieve the Rxjava package, to Baidu or Google, search Rxjava operator compose can understand.
After work, too late to explain too much, if you see more people, there is time to update the details.
Project Demo address (too Troublesome no separation module, directly to the project has not completed the framework put up):
The demo is uploading, and will go back to update
Rxjava memory leak resolution in Android and Rxjava encapsulation.