RxLifecycle有兩種使用方法:
1、bindToLifecycle直接綁定生命周期
Observable.interval(1, TimeUnit.SECONDS)
.doOnDispose(new Action() {
@Override
public void run() throws Exception {
Log.i(TAG, "Unsubscribing subscription from onStart()");
}
})
.compose(this.<Long>bindToLifecycle())//使用bindToLifecycle
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long num) throws Exception {
Log.i(TAG, "Started in onStart(), running until in onStop(): " + num);
}
});
2再姑、bindUntilEvent綁定特定的ActivityEvent
Observable.interval(1, TimeUnit.SECONDS)
.doOnDispose(new Action() {
@Override
public void run() throws Exception {
Log.i(TAG, "Unsubscribing subscription from onCreate()");
}
})
.compose(this.<Long>bindUntilEvent(ActivityEvent.PAUSE))//使用bindUntilEvent
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long num) throws Exception {
Log.i(TAG, "Started in onCreate(), running until onPause(): " + num);
}
});
原理其實(shí)一樣胳岂,只分析bindToLifecycle是怎么綁定Activity的生命周期的编整。
首先bindToLifecycle是通過compose操作的,compose比較常見乳丰,比如切換線程的時(shí)候掌测,用compose操作符讓代碼更好看些,compose操作的是個(gè)Transformer产园,跟進(jìn)去看,bindToLifecycle果然返回一個(gè)封裝了的LifecycleTransformer:
public final <T> LifecycleTransformer<T> bindToLifecycle() {
return RxLifecycleAndroid.bindActivity(lifecycleSubject);
}
public static <T> LifecycleTransformer<T> bindActivity(@NonNull final Observable<ActivityEvent> lifecycle) {
return bind(lifecycle, ACTIVITY_LIFECYCLE);
}
好汞斧,這里出現(xiàn)了兩個(gè)重要的東西lifecycleSubject和ACTIVITY_LIFECYCLE夜郁,bind方法將這兩個(gè)東西處理后,返回的LifecycleTransformer粘勒。lifecycleSubject和ACTIVITY_LIFECYCLE是什么竞端?看源碼:
private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();
lifecycleSubject原來是個(gè)BehaviorSubject,BehaviorSubject可以當(dāng)做Observable來發(fā)射消息庙睡,查看RxActivity或RxAppCompatActivity類的生命周期回調(diào)方法,lifecycleSubject都發(fā)送了該生命周期標(biāo)識乘陪,比如:
protected void onPause() {
lifecycleSubject.onNext(ActivityEvent.PAUSE);
super.onPause();
}
protected void onStop() {
lifecycleSubject.onNext(ActivityEvent.STOP);
super.onStop();
}
protected void onDestroy() {
lifecycleSubject.onNext(ActivityEvent.DESTROY);
super.onDestroy();
}
我們來想下统台,一般情況下我們都是希望在Activiy退出(onDestroy)后,取消訂閱消息啡邑,那么 lifecycleSubject.onNext(ActivityEvent.DESTROY)在onDestroy中發(fā)射后饺谬,就要通知該取消訂閱消息了,正好takeUntil操作符可以滿足要求谣拣,takeUntil操作符簡要說明如下:
//Observable1發(fā)射數(shù)據(jù)募寨,但是當(dāng)Observable2也發(fā)射數(shù)據(jù)時(shí),訂閱就取消了森缠。
Observable1
.takeUntil(Observable2)
.subscribe(new Consumer);
我們想要的正是在ActivityEvent.DESTROY消息發(fā)送后拔鹰,訂閱取消」蠛回到上面列肢,我們知道了lifecycleSubject是干什么用的了,lifecycleSubject就是發(fā)射生命周期標(biāo)識宾茂,通過這個(gè)來監(jiān)控Activity生命周期瓷马。
那ACTIVITY_LIFECYCLE是干什么用的?ACTIVITY_LIFECYCLE是個(gè)Function:
private static final Function<ActivityEvent, ActivityEvent> ACTIVITY_LIFECYCLE =
new Function<ActivityEvent, ActivityEvent>() {
@Override
public ActivityEvent apply(ActivityEvent lastEvent) throws Exception {
switch (lastEvent) {
case CREATE:
return ActivityEvent.DESTROY;
case START:
return ActivityEvent.STOP;
case RESUME:
return ActivityEvent.PAUSE;
case PAUSE:
return ActivityEvent.STOP;
case STOP:
return ActivityEvent.DESTROY;
case DESTROY:
throw new OutsideLifecycleException("Cannot bind to Activity lifecycle when outside of it.");
default:
throw new UnsupportedOperationException("Binding to " + lastEvent + " not yet implemented");
}
}
};
這個(gè)Function的作用就是返回訂閱消息所對應(yīng)的生命周期跨晴,意思是如果你在onCreate訂閱欧聘,那么就返回DESTROY,意味只有在Activity onDestroy的時(shí)候取消訂閱端盆。以下分析都依在DESTROY中取消訂閱為例怀骤。
lifecycleSubject和ACTIVITY_LIFECYCLE作用明白了,繼續(xù)往下走,bind方法里面是:
public static <T, R> LifecycleTransformer<T> bind(@Nonnull Observable<R> lifecycle, @Nonnull final Function<R, R> correspondingEvents) {
return bind(takeUntilCorrespondingEvent(lifecycle.share(), correspondingEvents));
}
輸入的lifecycleSubject和ACTIVITY_LIFECYCLE被takeUntilCorrespondingEvent處理了焕妙,這個(gè)方法才是RxLifecycle最精華的地方:
private static <R> Observable<Boolean> takeUntilCorrespondingEvent(final Observable<R> lifecycle, final Function<R, R> correspondingEvents) {
return Observable.combineLatest(
lifecycle.take(1).map(correspondingEvents),
lifecycle.skip(1),
new BiFunction<R, R, Boolean>() {
@Override
public Boolean apply(R bindUntilEvent, R lifecycleEvent) throws Exception {
return lifecycleEvent.equals(bindUntilEvent);
}
})
.onErrorReturn(Functions.RESUME_FUNCTION)
.filter(Functions.SHOULD_COMPLETE);
}
拆開看:
//這兩個(gè)其實(shí)就是lifecycleSubject蒋伦,可以理解為兩個(gè)Observable
lifecycle.take(1).map(correspondingEvents),//map操作符調(diào)用correspondingEvents(就是上面的ACTIVITY_LIFECYCLE)的作用上面說了,類似輸入CREATE焚鹊,輸出DESTROY
lifecycle.skip(1),//跳過之前發(fā)射的生命周期痕届,比如在onStart里發(fā)射,跳過去,只操作onStart之后的生命周期
combineLatest操作符的作用就是操作這兩個(gè)Observable(其實(shí)都是lifecycleSubject)研叫,再回到takeUntil操作符势决,只有在onDestroy的時(shí)候發(fā)射,才能取消訂閱蓝撇,而在其他生命周期,比如onPause陈莽,onStop這些不能取消渤昌,這時(shí)候我們有了第一個(gè)數(shù)據(jù)源lifecycle.take(1).map(correspondingEvents)返回的DESTROY,還有第二個(gè)數(shù)據(jù)源lifecycle.skip(1)返回的PAUSE走搁,STOP独柑,DESTROY這些訂閱后的生命周期,那么就可以操作:只有第二個(gè)數(shù)據(jù)等于第一個(gè)數(shù)據(jù)才會取消訂閱私植,于是回到源碼,通過combineLatest的第三個(gè)參數(shù)來完成這個(gè)比較:
new BiFunction<R, R, Boolean>() {
@Override
public Boolean apply(R bindUntilEvent, R lifecycleEvent) throws Exception{
return lifecycleEvent.equals(bindUntilEvent);//兩個(gè)數(shù)據(jù)源比較
}
})
好了忌栅,到了這一步,我們得到了每個(gè)生命周期回調(diào)時(shí)曲稼,takeUntil操作符操作的Observable索绪,類型是Boolean,只有DESTROY時(shí)返回true贫悄,其他生命周期來時(shí)返回false瑞驱。但是false不能返回啊,因?yàn)閠akeUntil一旦把false發(fā)射出去窄坦,那訂閱就取消了唤反,我們只想在true的時(shí)候才發(fā)射出去,filter操作符上場了:
Observable\\前面已經(jīng)得到的false或true,通過filter鸭津,只有true才發(fā)射
.filter(Functions.SHOULD_COMPLETE);
static final Predicate<Boolean> SHOULD_COMPLETE = new Predicate<Boolean>() {
@Override
public boolean test(Boolean shouldComplete) throws Exception {
return shouldComplete;
}
};
SHOULD_COMPLETE很簡單彤侍,輸入輸出一樣,但是完成了只有true才發(fā)射的要求逆趋。
至此盏阶,RxLifecycle通過bindToLifecycle綁定生命周期的原理應(yīng)該清楚了,再總結(jié)下:
1、在Activiy的每個(gè)生命周期回調(diào)里通過lifecycleSubject發(fā)射當(dāng)前生命周期標(biāo)識,比如發(fā)射A
2闻书、通過ACTIVITY_LIFECYCLE得到想要取消訂閱的生命周期標(biāo)識B
3般哼、在takeUntilCorrespondingEvent方法里比較A和B,得到是否相等的結(jié)果C
4惠窄、通過filter操作符只發(fā)射3中結(jié)果是true的C
5蒸眠、因?yàn)槭褂昧藅akeUntil操作符,一旦4里發(fā)射了杆融,那訂閱就取消了楞卡。
最后takeUntil是在哪里調(diào)用的呢,回到開始的LifecycleTransformer:
public final class LifecycleTransformer<T> implements ObservableTransformer<T, T>,
FlowableTransformer<T, T>,
SingleTransformer<T, T>,
MaybeTransformer<T, T>,
CompletableTransformer
{
@Override
public ObservableSource<T> apply(Observable<T> upstream) {
return upstream.takeUntil(observable);
}
.........
}