Android performance optimization leverages rxlifecycle to resolve Rxjava memory leaks

Source: Internet
Author: User

Objective:

In fact, Rxjava caused by the memory leak is I accidentally discovered, originally is want to understand how retrofit and Rxjava in the combination of how to solve through the adapter mode, the results found that Rxjava will cause memory leaks, All want to find out the data to learn how to solve the rxjava caused by the memory leak, it is found that the use of Rxlifecycle Open source framework can be solved, this weekend to learn how to use the rxlifecycle.

Reference the background of the leak:

Rxjava, as a responsive programming framework, is now a well-known programming community, and its concise coding style, easy-to-use easy-to-read chain method invocation, and powerful asynchronous support make Rxjava widely used, which makes it easier to control and switch threads through the thread scheduler. If the worker exits activity or fragment before the end of execution, the activity or fragment cannot be released causing a memory leak.

What is Rxlifecycle?

Rxlifecycle is an open-source framework developed by Trello to address memory leaks caused by Rxjava.

GitHub Address: Https://github.com/trello/RxLifecycle

How do I use rxlifecycle? 1.) Add references in the Build.gradle file
Compile ' com.trello:rxlifecycle:1.0 '//If you are want to bind to Android-specific lifecyclescompile ' Com.trello: rxlifecycle-android:1.0 '//If you want pre-written activities and fragments can subclass as Providerscompile ' Com.trel lo:rxlifecycle-components:1.0 '//If you want the use of Navi for Providerscompile ' com.trello:rxlifecycle-navi:1.0 '//If you w Ant to use Kotlin syntaxcompile ' com.trello:rxlifecycle-kotlin:1.0 '

Add me according to your needs here are the following two

Compile ' com.trello:rxlifecycle:1.0 ' compile ' com.trello:rxlifecycle-components:1.0 '
2.) According to different needs activity inheritance rxactivity, fragment inherit Rxfragment
 Public classMainActivity7extendsrxactivity {PrivateTextView Mtextview; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Mtextview=(TextView) Findviewbyid (R.id.text); //simulating memory leaksTestrxjava ();    Finish (); }    Private voidTestrxjava () {observable.create (NewObservable.onsubscribe<string>() {@Override Public voidCall (SUBSCRIBER&LT;?SuperString>subscriber) {                inti = 0;  while(I < 1000000000) {i++;                } subscriber.onnext (String.valueof (i));            Subscriber.oncompleted (); }}). Compose ( This.<string>binduntilevent (Activityevent.pause)). Subscribeon (Schedulers.io ()). Observeon (Androidsch Edulers.mainthread ()). Subscribe (NewAction1<string>() {@Override Public voidCall (String s) {mtextview.settext (s);    }                }); } @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Lapplication.getrefwatcher (). Watch ( This); }}

Currently supported Activity/fragment structure diagram

3.) Use the Bindtolifecycle () method

The subclass uses the compose operator in observable to invoke, complete observable published events and current component bindings to achieve lifecycle synchronization. This enables automatic cancellation of the observable subscription at the end of the current component life cycle.

Observable.create (NewObservable.onsubscribe<string>() {@Override Public voidCall (SUBSCRIBER&LT;?SuperString>subscriber) {                inti = 0;  while(I < 1000000000) {i++;                } subscriber.onnext (String.valueof (i));            Subscriber.oncompleted (); }}). Compose ( This.<string>bindtolifecycle ()). Subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ()). Subscribe (NewAction1<string>() {@Override Public voidCall (String s) {mtextview.settext (s); }                });
4.) use Binduntilevent () mode

Use the Activityevent class, where create, START, RESUME, PAUSE, STOP, destroy correspond to the methods in the life cycle, respectively. Use Binduntilevent to specify which lifecycle method calls are unsubscribed.

Observable.create (NewObservable.onsubscribe<string>() {@Override Public voidCall (SUBSCRIBER&LT;?SuperString>subscriber) {                inti = 0;  while(I < 1000000000) {i++;                } subscriber.onnext (String.valueof (i));            Subscriber.oncompleted (); }}). Compose ( This.<string>binduntilevent (Activityevent.pause)). Subscribeon (Schedulers.io ()). Observeon (Androidsch Edulers.mainthread ()). Subscribe (NewAction1<string>() {@Override Public voidCall (String s) {mtextview.settext (s); }                });
5.) Customizing a Rxactivity/rxfragment

Only need the activity that you want to implement Lifecycleprovider<activityevent> interface can, here paste out rxactivity source code imitate it to make next change.

 Public Abstract classRxactivityextendsActivityImplementsLifecycleprovider<activityevent> {    Private FinalBehaviorsubject<activityevent> Lifecyclesubject =behaviorsubject.create ();  Publicrxactivity () {} @NonNull @CheckResult Public FinalObservable<activityevent>lifecycle () {return  This. lifecyclesubject.asobservable (); } @NonNull @CheckResult Public Final<T> lifecycletransformer<t>binduntilevent (@NonNull activityevent event) {returnRxlifecycle.binduntilevent ( This. Lifecyclesubject, event); } @NonNull @CheckResult Public Final<T> lifecycletransformer<t>bindtolifecycle () {returnRxlifecycleandroid.bindactivity ( This. Lifecyclesubject); } @CallSuperprotected voidonCreate (@Nullable Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);  This. Lifecyclesubject.onnext (activityevent.create); } @CallSuperprotected voidOnStart () {Super. OnStart ();  This. Lifecyclesubject.onnext (Activityevent.start); } @CallSuperprotected voidOnresume () {Super. Onresume ();  This. Lifecyclesubject.onnext (Activityevent.resume); } @CallSuperprotected voidOnPause () { This. Lifecyclesubject.onnext (Activityevent.pause); Super. OnPause (); } @CallSuperprotected voidOnStop () { This. Lifecyclesubject.onnext (Activityevent.stop); Super. OnStop (); } @CallSuperprotected voidOnDestroy () { This. Lifecyclesubject.onnext (Activityevent.destroy); Super. OnDestroy (); }}
Summarize:

This paper summarizes the problem of Rxjava memory leakage through rxlifecycle, but also gives us a warning, the good frame has its good side also has the bad side, at this time completes the technology choice and avoids the risk is very important.

Android performance optimization leverages rxlifecycle to resolve Rxjava memory leaks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.