RxLifecycle原理分析

RxLifecycle源码地址

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.bindToLifecycle())//使用bindToLifecycle
            .subscribe(new Consumer() {
                @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.bindUntilEvent(ActivityEvent.PAUSE))//使用bindUntilEvent
            .subscribe(new Consumer() {
                @Override
                public void accept(Long num) throws Exception {
                    Log.i(TAG, "Started in onCreate(), running until onPause(): " + num);
                }
            });

原理其实一样,只分析bindToLifecycle是怎么绑定Activity的生命周期的。
首先bindToLifecycle是通过compose操作的,compose比较常见,比如切换线程的时候,用compose操作符让代码更好看些,compose操作的是个Transformer,跟进去看,bindToLifecycle果然返回一个封装了的LifecycleTransformer:

public final  LifecycleTransformer bindToLifecycle() {
     return RxLifecycleAndroid.bindActivity(lifecycleSubject);
}

public static  LifecycleTransformer bindActivity(@NonNull final Observable lifecycle) {
        return bind(lifecycle, ACTIVITY_LIFECYCLE);
}

好,这里出现了两个重要的东西lifecycleSubject和ACTIVITY_LIFECYCLE,bind方法将这两个东西处理后,返回的LifecycleTransformer。lifecycleSubject和ACTIVITY_LIFECYCLE是什么?看源码:

private final BehaviorSubject lifecycleSubject = BehaviorSubject.create();

lifecycleSubject原来是个BehaviorSubject,BehaviorSubject可以当做Observable来发射消息,查看RxActivity或RxAppCompatActivity类的生命周期回调方法,lifecycleSubject都发送了该生命周期标识,比如:

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中发射后,就要通知该取消订阅消息了,正好takeUntil操作符可以满足要求,takeUntil操作符简要说明如下:

//Observable1发射数据,但是当Observable2也发射数据时,订阅就取消了。
Observable1
 .takeUntil(Observable2)
 .subscribe(new Consumer);

我们想要的正是在ActivityEvent.DESTROY消息发送后,订阅取消。回到上面,我们知道了lifecycleSubject是干什么用的了,lifecycleSubject就是发射生命周期标识,通过这个来监控Activity生命周期。
那ACTIVITY_LIFECYCLE是干什么用的?ACTIVITY_LIFECYCLE是个Function:

  private static final Function ACTIVITY_LIFECYCLE =
        new Function() {
            @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");
                }
            }
        };

这个Function的作用就是返回订阅消息所对应的生命周期,意思是如果你在onCreate订阅,那么就返回DESTROY,意味只有在Activity onDestroy的时候取消订阅。以下分析都依在DESTROY中取消订阅为例。
lifecycleSubject和ACTIVITY_LIFECYCLE作用明白了,继续往下走,bind方法里面是:

 public static  LifecycleTransformer bind(@Nonnull Observable lifecycle, @Nonnull final Function correspondingEvents) {
        return bind(takeUntilCorrespondingEvent(lifecycle.share(), correspondingEvents));
    }

输入的lifecycleSubject和ACTIVITY_LIFECYCLE被takeUntilCorrespondingEvent处理了,这个方法才是RxLifecycle最精华的地方:

private static  Observable takeUntilCorrespondingEvent(final Observable lifecycle, final Function correspondingEvents) {
        return Observable.combineLatest(
            lifecycle.take(1).map(correspondingEvents),
            lifecycle.skip(1),
            new BiFunction() {
                @Override
                public Boolean apply(R bindUntilEvent, R lifecycleEvent) throws Exception {
                    return lifecycleEvent.equals(bindUntilEvent);
                }
            })
            .onErrorReturn(Functions.RESUME_FUNCTION)
            .filter(Functions.SHOULD_COMPLETE);
    }

拆开看:

//这两个其实就是lifecycleSubject,可以理解为两个Observable
lifecycle.take(1).map(correspondingEvents),//map操作符调用correspondingEvents(就是上面的ACTIVITY_LIFECYCLE)的作用上面说了,类似输入CREATE,输出DESTROY
lifecycle.skip(1),//跳过之前发射的生命周期,比如在onStart里发射,跳过去,只操作onStart之后的生命周期

combineLatest操作符的作用就是操作这两个Observable(其实都是lifecycleSubject),再回到takeUntil操作符,只有在onDestroy的时候发射,才能取消订阅,而在其他生命周期,比如onPause,onStop这些不能取消,这时候我们有了第一个数据源lifecycle.take(1).map(correspondingEvents)返回的DESTROY,还有第二个数据源lifecycle.skip(1)返回的PAUSE,STOP,DESTROY这些订阅后的生命周期,那么就可以操作:只有第二个数据等于第一个数据才会取消订阅,于是回到源码,通过combineLatest的第三个参数来完成这个比较:

new BiFunction() {
     @Override
     public Boolean apply(R bindUntilEvent, R lifecycleEvent) throws Exception{
          return lifecycleEvent.equals(bindUntilEvent);//两个数据源比较
      }
 })

好了,到了这一步,我们得到了每个生命周期回调时,takeUntil操作符操作的Observable,类型是Boolean,只有DESTROY时返回true,其他生命周期来时返回false。但是false不能返回啊,因为takeUntil一旦把false发射出去,那订阅就取消了,我们只想在true的时候才发射出去,filter操作符上场了:

Observable\\前面已经得到的false或true,通过filter,只有true才发射
.filter(Functions.SHOULD_COMPLETE);

static final Predicate SHOULD_COMPLETE = new Predicate() {
        @Override
        public boolean test(Boolean shouldComplete) throws Exception {
            return shouldComplete;
        }
};

SHOULD_COMPLETE很简单,输入输出一样,但是完成了只有true才发射的要求。
至此,RxLifecycle通过bindToLifecycle绑定生命周期的原理应该清楚了,再总结下:
1、在Activiy的每个生命周期回调里通过lifecycleSubject发射当前生命周期标识,比如发射A
2、通过ACTIVITY_LIFECYCLE得到想要取消订阅的生命周期标识B
3、在takeUntilCorrespondingEvent方法里比较A和B,得到是否相等的结果C
4、通过filter操作符只发射3中结果是true的C
5、因为使用了takeUntil操作符,一旦4里发射了,那订阅就取消了。

最后takeUntil是在哪里调用的呢,回到开始的LifecycleTransformer:

public final class LifecycleTransformer implements ObservableTransformer,
                                                      FlowableTransformer,
                                                      SingleTransformer,
                                                      MaybeTransformer,
                                                      CompletableTransformer
{
 @Override
    public ObservableSource apply(Observable upstream) {
        return upstream.takeUntil(observable);
    }
    .........
}

你可能感兴趣的:(RxLifecycle原理分析)