依賴項:android
//AutoDispose解決RxJava內存泄漏 implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha2' implementation 'com.uber.autodispose:autodispose:1.1.0' implementation 'com.uber.autodispose:autodispose-android:1.1.0' implementation 'com.uber.autodispose:autodispose-android-archcomponents:1.1.0' implementation 'com.uber.autodispose:autodispose-android-archcomponents-test:1.1.0'
代碼樣例:app
Observable.interval(1, TimeUnit.SECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) //AutoDispose RxJava內存泄漏處理 //.as(AutoDispose.<Long>autoDisposable(AndroidLifecycleScopeProvider.from(SecondActivity.this, Event.ON_DESTROY))) .subscribe(new Observer<Long>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Long aLong) { } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); 使用AndroidStudio中的profile進行內存分析查看:![](https://s4.51cto.com/images/blog/201812/21/34d6c1bfe8d1349c3c5bc1e494fd2cbd.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=) 點擊這個圖標啓動app,選擇你的手機,對應包名,雙擊MEMORY視圖 查看使用AutoDispose於不使用的區別看對應類內存是否回收了 ![](https://s4.51cto.com/images/blog/201812/21/e351f2ccce71828b2e6f9296dc7bfbaa.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=) 注意點:
項目依賴的是下面這兩個,不然直接使用support-v7中的AppCompatActivity調用接口時類型匹配不上
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha2'
```ide