解決rxjava導致的記憶體流失

來源:互聯網
上載者:User
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。 1.使用取消訂閱管理器:CompositeSubscription,讓CompositeSubscription持有所有的請求。統一取消。
//這代碼是mvp中使用的 public class LoginPresenter implements BasePresenter{    private UserLoginContract mView;//當前的頁面    private CompositeSubscription msubscription;//管理所有的訂閱    public LoginPresenter(UserLoginContract mView) {        this.mView = mView;        this.mView.setPresenter(this);        this.msubscription = new CompositeSubscription();    }    /**     * 擷取class     */    public void getClassInfo() {        HashMap<String, String> map = new HashMap<>();        map.put("id", "3");        Subscription i  = ApiManger.getIntance().api.getClass(map)                .flatMap(new Func1<BaseBean<List<SchoolClass>>, Observable<List<SchoolClass>>>() {                    @Override                    public Observable<List<SchoolClass>> call(BaseBean<List<SchoolClass>> listBaseBean) {                        return new ApiInterceptor().flatResult(listBaseBean);                    }                })                .compose(RxSchedulers.<List<SchoolClass>>IO_Main())                .subscribe(new Subscriber<List<SchoolClass>>() {                    @Override                    public void onCompleted() {                        //擷取資料完成                        mView.loginSuccess();                    }                    @Override                    public void onError(Throwable e) {                       ApiException apiException = (ApiException) e;                        mView.showToast(apiException.getRespMSg());                    }                    @Override                    public void onNext(List<SchoolClass> schoolClasses) {                        //得到資料,在頁面可以進行資料繫結操作                    }                });        this.msubscription.add(i);//把訂閱加入管理集合中    }    @Override    public void onDestroy() {        //在activity結束生命週期的時候取消訂閱,解除對context的引用        if(msubscription != null){            this.msubscription.unsubscribe();        }    }}public class BaseActivity extends AppCompatActivity {    public BasePresenter presenter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);    }    @Override    protected void onDestroy() {        super.onDestroy();        presenter.onDestroy();    }}
2.使用Rxlifecycle第三方庫,完成Observable發布的事件和當前的組件綁定,實現生命週期同步。組件生命週期結束時,自動取消對Observable訂閱。 項目依賴:
//rxlifecycle 生命週期同步    compile 'com.trello:rxlifecycle:0.6.1'    compile 'com.trello:rxlifecycle-components:0.6.1'
Rxlifecycle 使用 Activity/Fragment需繼承RxAppCompatActivity/RxFragment,目前支援的有RxAppCompatActivity、RxFragment、RxDialogFragment、RxFragmentActivity。 一、bindToLifecycle()方法 在子類使用Observable中的compose操作符,調用,完成Observable發布的事件和當前的組件綁定,實現生命週期同步。從而實現當前組件生命週期結束時,自動取消對Observable訂閱。
   Observable.interval(1, TimeUnit.SECONDS)        .compose(this.bindToLifecycle())            .subscribe(new Action1<Long>() {                 @Override                public void call(Long num) {                    Log.i(TAG, "  " +num);                }            });
二、bindUntilEvent() 方法

使用ActivityEvent類,其中的CREATE、START、 RESUME、PAUSE、STOP、 DESTROY分別對應生命週期內的方法。使用bindUntilEvent指定在哪個生命週期方法調用時取消訂閱。

 Observable.interval(1, TimeUnit.SECONDS)         .compose(this.bindUntilEvent(ActivityEvent.PAUSE))           .subscribe(mSub);
3.自己取消訂閱:subscription.unsubscribe() ;
public abstract class BaseFragment extends Fragment {    protected Subscription subscription;    @Override    public void onDestroyView() {        super.onDestroyView();        unsubscribe();    }    protected void unsubscribe() {        if (subscription != null && !subscription.isUnsubscribed()) {            subscription.unsubscribe();        }    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.