AutoDispose源码解析

作者: 雯艺雪 | 来源:发表于2019-08-17 22:09 被阅读16次

    0.前言

    “面试结束后,面试官问我还有什么要问的吗?我问‘您对我此次面试有什么评价吗?’,面试官回答:‘我面试过很多人,简历上总写会什么框架什么框架的,结果一问框架原理立马就崩溃了......’”
    这是我一位同学的面试经历。框架不仅仅要会用还要知道其原理,了解其原理就会发现,其实框架的设计原理都差不多。笔者写过几篇框架分析的几篇文章ViewModel源码解析 ,LiveData源码解析
    ,Glide源码解析通过这几篇框架原理的分析发现阅读框架源码分析原理并不难,希望读者勇敢的跨出这一步,这将对你有很大帮助。

    1.AutoDispose

    AutoDispose是什麽?rxjava的使用过程中,如果不及时对订阅的观察者在activity销毁时取消订阅,就有可能引发内存泄漏(内存泄漏和内存溢出不同,切记),因此必须手动在取消的地方进行取消订阅,但是每次都要这样写“多余”的代码实在麻烦,于是就诞生了RxLifeCycle和AutoDispose(推荐使用AutoDispose,详见 为什么不使用 RxLifecycle?
    ),两者都用于实现根据lifecycleOwner的生命周期自动取消订阅

    • 导入

    //autodispose
    implementation 'com.uber.autodispose:autodispose-android-archcomponents:1.0.0-RC2'
    implementation 'com.uber.autodispose:autodispose:1.0.0-RC2'

    • 使用
    observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .`as`(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner)))
                    .subscribe()
    

    本文主要介绍源码分析,详细使用可以参考笔者这篇文章
    LiveData+ViewModel+RxJava2+autoDisposable解决内存泄漏

    2.分析

    切入点:

    `as`(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOw
    

    先来看看from方法:

     public static AndroidLifecycleScopeProvider from(LifecycleOwner owner) {
        return from(owner.getLifecycle());//从lifecycleOwner中取出lifecycle
      }
    
    public static AndroidLifecycleScopeProvider from(Lifecycle lifecycle) {
        return from(lifecycle, DEFAULT_CORRESPONDING_EVENTS);
      }
    /**
       * Creates a {@link AndroidLifecycleScopeProvider} for Android Lifecycles.
       *
       * @param lifecycle the lifecycle to scope for.
       * @param boundaryResolver function that resolves the event boundary.
       * @return a {@link AndroidLifecycleScopeProvider} against this lifecycle.
       */
      public static AndroidLifecycleScopeProvider from(Lifecycle lifecycle,
          CorrespondingEventsFunction<Lifecycle.Event> boundaryResolver) {
      //可以看到from方法实际上就是创建包含lifecycle和boundaryResolver的ScopeProvider
        return new AndroidLifecycleScopeProvider(lifecycle, boundaryResolver);
      }
    
    private AndroidLifecycleScopeProvider(Lifecycle lifecycle,
          CorrespondingEventsFunction<Lifecycle.Event> boundaryResolver) {
      //将lifecycle包装成LifecycleEventsObservable
        this.lifecycleObservable = new LifecycleEventsObservable(lifecycle);
        this.boundaryResolver = boundaryResolver;
      }
    
    //代码1,重点!
     private static final CorrespondingEventsFunction<Lifecycle.Event> DEFAULT_CORRESPONDING_EVENTS =
          new CorrespondingEventsFunction<Lifecycle.Event>() {
            @Override public Lifecycle.Event apply(Lifecycle.Event lastEvent) throws OutsideScopeException {
              switch (lastEvent) {
                case ON_CREATE:
                  return Lifecycle.Event.ON_DESTROY;
                case ON_START:
                  return Lifecycle.Event.ON_STOP;
                case ON_RESUME:
                  return Lifecycle.Event.ON_PAUSE;
                case ON_PAUSE:
                  return Lifecycle.Event.ON_STOP;
                case ON_STOP:
                case ON_DESTROY:
                default:
                  throw new LifecycleEndedException("Lifecycle has ended! Last event was " + lastEvent);
              }
            }
          };
    
    

    AndroidLifecycleScopeProvider实现LifecycleScopeProvider接口,LifecycleScopeProvider继承于ScopeProvider
    代码1这里定义的是lifecycle生命周期对应的取消订阅的生命周期,怎么理解呢?在使用AutoDispose绑定observable时,如果在Activity的onStart()绑定,就会在onStop()方法自动取消订阅;在onCreate()订阅,就在onDestrory()方法自动取消订阅等等;现在知道为什么了吧。这段代码主要就是用于获取对应的取消订阅的周期。
    接下来是

    • autoDisposable(ScopeProvider)
     public static <T> AutoDisposeConverter<T> autoDisposable(final ScopeProvider provider) {
        checkNotNull(provider, "provider == null");
        return autoDisposable(Completable.defer(new Callable<CompletableSource>() {
          @Override public CompletableSource call() throws Exception {
            try {
              return provider.requestScope();//从provider中取出CompletableSource
            } catch (OutsideScopeException e) {
              Consumer<? super OutsideScopeException> handler = AutoDisposePlugins.getOutsideScopeHandler();
              if (handler != null) {
                handler.accept(e);
                return Completable.complete();
              } else {
                return Completable.error(e);
              }
            }
          }
        }));
      }
    
    • provider的requestCode方法:
     @Override public CompletableSource requestScope() {
        return LifecycleScopes.resolveScopeFromLifecycle(this);//调用LifecycleScopes的静态方法获取CompletableSource,传递provider本身作为
      }
    
    • resolveScopeFromLifecycle方法
     public static <E> CompletableSource resolveScopeFromLifecycle(final LifecycleScopeProvider<E> provider)
          throws OutsideScopeException {
        return resolveScopeFromLifecycle(provider, true);
      }
    
    public static <E> CompletableSource resolveScopeFromLifecycle(final LifecycleScopeProvider<E> provider,
          final boolean checkEndBoundary) throws OutsideScopeException {
        E lastEvent = provider.peekLifecycle();//获取最新的lifecycle生命周期
        //即DEFAULT_CORRESPONDING_EVENTS 
        CorrespondingEventsFunction<E> eventsFunction = provider.correspondingEvents();
        if (lastEvent == null) {
          throw new LifecycleNotStartedException();
        }
        E endEvent;
        try {
          endEvent = eventsFunction.apply(lastEvent);//将当前生命周期传递过去获取对应取消订阅的周期
        } catch (Exception e) {
          if (checkEndBoundary && e instanceof LifecycleEndedException) {
            Consumer<? super OutsideScopeException> handler = AutoDisposePlugins.getOutsideScopeHandler();
            if (handler != null) {
              try {
                handler.accept((LifecycleEndedException) e);
    
                // Swallowed the end exception, just silently dispose immediately.
                return Completable.complete();
              } catch (Exception e1) {
                return Completable.error(e1);
              }
            }
            throw e;
          }
          return Completable.error(e);
        }
        return resolveScopeFromLifecycle(provider.lifecycle(), endEvent);
      }
    
     public static <E> CompletableSource resolveScopeFromLifecycle(Observable<E> lifecycle, final E endEvent) {
        @Nullable Comparator<E> comparator = null;
        //如果已存在,返回它(防止重复操作)
        if (endEvent instanceof Comparable) {
          //noinspection unchecked
          comparator = (Comparator<E>) COMPARABLE_COMPARATOR;
        }
        return resolveScopeFromLifecycle(lifecycle, endEvent, comparator);
      }
    
     public static <E> CompletableSource resolveScopeFromLifecycle(Observable<E> lifecycle,
          final E endEvent,
          @Nullable final Comparator<E> comparator) {
        Predicate<E> equalityPredicate;
        if (comparator != null) {
          equalityPredicate = new Predicate<E>() {
            @Override public boolean test(E e) {
              //如果e超过了endEvent,返回true
              return comparator.compare(e, endEvent) >= 0;
            }
          };
        } else {
          equalityPredicate = new Predicate<E>() {
            @Override public boolean test(E e) {
              return e.equals(endEvent);
            }
          };
        }
        return lifecycle.skip(1)
            .takeUntil(equalityPredicate)//结束条件为e超过endEvent后
            .ignoreElements();
      }
    

    绕了这么大的圈子,就是为了获取到CompletableSource,之后作为Completable.defer()的参数,Completable又作为autoDisposable的参数返回给as方法。
    autoDisposable接受Completable参数之后:

     public static <T> AutoDisposeConverter<T> autoDisposable(final CompletableSource scope) {
        checkNotNull(scope, "scope == null");
        return new AutoDisposeConverter<T>() {
          @Override public ParallelFlowableSubscribeProxy<T> apply(final ParallelFlowable<T> upstream) {
            return new ParallelFlowableSubscribeProxy<T>() {
              @Override public void subscribe(Subscriber<? super T>[] subscribers) {
                new AutoDisposeParallelFlowable<>(upstream, scope).subscribe(subscribers);//订阅处理subscribers
              }
            };
          }
          ......
          /`省略部分代码``/
      }
    

    代码虽多,总结起来就是干了两件事:


    AutoDispose.png

    关于AutoDispose就介绍到这里,水平有限,有错误请指出来,您的支持是对我最大的鼓励!!!
    原创文章,转载附上https://www.jianshu.com/p/ee31c26a3707

    相关文章

      网友评论

        本文标题:AutoDispose源码解析

        本文链接:https://www.haomeiwen.com/subject/txnksctx.html