Rxlifecycle使用非常方便簡單,如下:
1.集成
build.gradle添加
//Rxlifecycle compile 'com.trello:rxlifecycle:0.3.1' compile 'com.trello:rxlifecycle-components:0.3.1' //Rxjava compile 'io.reactivex:rxjava:1.0.16'
Components包中包含RxActivity、RxFragment等等,可以用Rxlifecycle提供的,也可以自定義。
2.Sample解析
官方sample源碼: 兩種使用方法:
1.手動設置取消訂閱的時機,例子1、例子3
2.綁定生命周期,自動取消訂閱,例子2
public class MainActivity extends RxAppCompatActivity { //Note:Activity需要繼承RxAppCompatActivity,fragment需要繼承RxFragment,等等 //可以使用的組件在components包下面 private static final String TAG = "RxLifecycle"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate()"); setContentView(R.layout.activity_main); // Specifically bind this until onPause() //Note:例子1: Observable.interval(1, TimeUnit.SECONDS) .doOnUnsubscribe(new Action0() { @Override public void call() { Log.i(TAG, "Unsubscribing subscription from onCreate()"); } }) //Note:手動設置在activity onPause的時候取消訂閱 .compose(this.<Long>bindUntilEvent(ActivityEvent.PAUSE)) .subscribe(new Action1<Long>() { @Override public void call(Long num) { Log.i(TAG, "Started in onCreate(), running until onPause(): " + num); } }); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart()"); //Note:例子2: // Using automatic unsubscription, this should determine that the correct time to // unsubscribe is onStop (the opposite of onStart). Observable.interval(1, TimeUnit.SECONDS) .doOnUnsubscribe(new Action0() { @Override public void call() { Log.i(TAG, "Unsubscribing subscription from onStart()"); } }) //Note:bindToLifecycle的自動取消訂閱示例,因為是在onStart的時候調用,所以在onStop的時候自動取消訂閱 .compose(this.<Long>bindToLifecycle()) .subscribe(new Action1<Long>() { @Override public void call(Long num) { Log.i(TAG, "Started in onStart(), running until in onStop(): " + num); } }); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume()"); //Note:例子3: // `this.<Long>` is necessary if you're compiling on JDK7 or below. // If you're using JDK8+, then you can safely remove it. Observable.interval(1, TimeUnit.SECONDS) .doOnUnsubscribe(new Action0() { @Override public void call() { Log.i(TAG, "Unsubscribing subscription from onResume()"); } }) //Note:手動設置在activity onDestroy的時候取消訂閱 .compose(this.<Long>bindUntilEvent(ActivityEvent.DESTROY)) .subscribe(new Action1<Long>() { @Override public void call(Long num) { Log.i(TAG, "Started in onResume(), running until in onDestroy(): " + num); } }); } ...