RxLifecycle是什麼?
This library allows one to automatically complete sequences based on a second lifecycle stream.
This capability is useful in Android, where incomplete subscriptions can cause memory leaks.
通俗的說:可以通過綁定生命週期的方式,來解決內存泄漏的問題
開源地址
rxlifecycle是trello開發的用於解決RxJava引起的內存泄漏的開源框架。傳送門
Android studio中的依賴與使用
1.)在build.gradle文件中添加依賴
// RxLifecycle基礎庫
compile 'com.trello.rxlifecycle2:rxlifecycle:2.1.0'
// Android組件庫,裏面定義了例如RxAppCompatActivity、RxFragment之類的Android組件
compile 'com.trello.rxlifecycle2:rxlifecycle-components:2.1.0'
2.)根據不同的需要Activity繼承RxActivity ,Fragment繼承RxFragment
public class MainActivity7 extends RxActivity {
private TextView mTextView;
private static final String TAG = "RxLifecycle";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text);
Observable.interval(1, TimeUnit.SECONDS)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
Log.i(TAG, "Unsubscribing subscription from onCreate()");
}
})
.subscribe(new Action1<Long>() {
@Override
public void call(Long num) {
Log.i(TAG, "Started in onCreate(), running until onPause(): " + num);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
當activity對象被銷燬,而我們的在rxjava中執行一些耗時的操作(例如:網絡訪問–>成功獲取數據–>刷新UI;文件的存儲等),就會造成內存泄露的現象。
3.)使用bindToLifecycle()的方式 —->綁定生命週期,自動取消訂閱
完成Observable發佈的事件和當前的組件綁定,實現生命週期同步。從而實現當前組件生命週期結束時,自動取消對Observable訂閱。
Observable.interval(1, TimeUnit.SECONDS)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
Log.i(TAG, "Unsubscribing subscription from onCreate()");
}
})
//Note:bindToLifecycle的自動取消訂閱示例,因爲是在onStart的時候調用,所以在onStop的時候自動取消訂閱
.compose(this.<Long>bindToLifecycle())
.subscribe(new Action1<Long>() {
@Override
public void call(Long num) {
Log.i(TAG, "Started in onCreate(), running until onPause(): " + num);
}
});
}
4.)使用bindUntilEvent()方式—>手動設置取消訂閱的時機
使用CREATE、START、 RESUME、PAUSE、STOP、 DESTROY分別對應生命週期內的方法。使用bindUntilEvent指定在哪個生命週期方法調用時取消訂閱。
Observable.interval(1, TimeUnit.SECONDS)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
Log.i(TAG, "Unsubscribing subscription from onCreate()");
}
})
//Note:bindUntilEvent手動設置在activity onDestroy的時候取消訂閱
.compose(this.<Long>bindUntilEvent(ActivityEvent.DESTROY))
.subscribe(new Action1<Long>() {
@Override
public void call(Long num) {
Log.i(TAG, "Started in onCreate(), running until onPause(): " + num);
}
});
}