利用 NavUtil,你能夠在 Activity 或 Fragment 的生命週期發生變化時,中止訂閱你的 Observable。maven
在Activity 中,爲你的 Observable 應用 compose 操做符,以下所示:ide
// 假設這是你的 Observable Observable.interval(1, TimeUnit.SECONDS) // 你的 Observable 將在 Activity 的 OnStopped 觸發後中止發射 .compose(NavUtil.<Long>subscribeUtilEvent(this, LifecycleEvent.ON_STOPPED)) .subscribe(new Subscriber<Long>() { @Override public void onCompleted() { Log.d(TAG, "onStart onCompleted() called"); } @Override public void onError(Throwable e) { Log.d(TAG, "onStart onError() called with: e = [" + e + "]"); } @Override public void onNext(Long aLong) { Log.d(TAG, "onStart onNext() called with: aLong = [" + aLong + "]"); } });
在 Fragment 中的用法以下所示:this
// 假設這是你的 Observable Observable.interval(1, TimeUnit.SECONDS) // 你的 Observable 將在 Activity 的 onPaused 觸發後中止發射 .compose(NavUtil.<Long>subscribeUtilEvent(this, LifecycleEvent.ON_PAUSED)) .subscribe(new Subscriber<Long>() { @Override public void onCompleted() { Log.d(TAG, "onCompleted() called"); } @Override public void onError(Throwable e) { Log.d(TAG, "onError() called with: e = [" + e + "]"); } @Override public void onNext(Long aLong) { Log.d(TAG, "onNext() called with: aLong = [" + aLong + "]"); } });
目前支持的生命週期事件以下所示:spa
public enum LifecycleEvent { ON_PAUSED, ON_STOPPED, ON_SAVE_INSTANCE_STATE, ON_DESTROYED, ON_VIEW_DESTORYED, ON_DETACHED, }
compile 'com.legendmohe.maven:navutil:x.y'