RxJava网络异步调用绑定UI生命周期

  • 简述

    因为Android UI组件通常会频繁性的创建销毁,在搭配异步操作时,子线程持有UI组件引用,而子线程通常用来执行耗时操作,当子线程运行期间UI组件被销毁时,UI组件实例会因为被引用而无法被释放内存占用,所以很容易导致内存泄露。

    之前分析过RxJava和Retrofit结合使用的源码,其中最后调用了compose(ObservableTransFormer)方法,传入lifecycleProvider.bindToLifecycle()实现和Android UI组件生命周期绑定,以解决UI组件内存泄漏问题,这篇文章就来分析一下是如何实现的。

  • 源码分析

    前面分析过,ViewModel中调用subscribe的是一个compose返回的Observable,我们就从这里开始分析:

    @CheckReturnValue
    @SchedulerSupport(SchedulerSupport.NONE)
    public final <R> Observable<R> compose(ObservableTransformer<? super T, ? extends R> composer) {
         
        return wrap(((ObservableTransformer<T, R>) ObjectHelper.requireNonNull(composer, "composer is null")).apply(this));
    }
    

    wrap:

    @CheckReturnValue
    @SchedulerSupport(SchedulerSupport.NONE)
    public static <T> Observable<T> wrap(ObservableSource<T> source) {
         
        ObjectHelper.requireNonNull(source, "source is null");
        if (source instanceof Observable) {
         
            return RxJavaPlugins.onAssembly((Observable<T>)source);
        }
        return RxJavaPlugins.onAssembly(new ObservableFromUnsafeSource<T>(source));
    }
    

    会返回一个ObservableFromUnsafeSource对象,当我们调用subscribe的时候就是调用它的subscribeActual:

    @Override
    protected void subscribeActual(Observer<? super T> observer) {
         
        source.subscribe(observer);
    }
    

    observer就是前面ViewModel传入的HttpObserver,source是((ObservableTransformer<T, R>) ObjectHelper.requireNonNull(composer, “composer is null”)).apply(this),composer也就是前面传入的lifecycle.bindToLifecycle(),lifecycle是啥,是LifecycleProvider接口的实例,那LifecycleProvider的实现类是什么呢?RxJava针对AndroidUI组件(Activity、Fragment)实现了继承自AppCompatActivity、Fragment等的LifecycleProvider的实现类RxAppCompatActivity、RxFragment等。

    RxAppCompatActivity中的bindToLifecycle是:

    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();
    
    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
         
        return RxLifecycleAndroid.bindActivity(lifecycleSubject);
    }
    

    RxFragment中的是:

    private final BehaviorSubject<FragmentEvent> lifecycleSubject = BehaviorSubject.create();
    
    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
         
        return RxLifecycleAndroid.bindFragment(lifecycleSubject);
    }
    

    BehaviorSubject.create:

    @CheckReturnValue
    @NonNull
    public static <T> BehaviorSubject<T> create() {
         
        return new BehaviorSubject<T>();
    }
    

    再看bindActivity和bindFragment:

    @NonNull
    @CheckResult
    public static <T> LifecycleTransformer<T> bindActivity(@NonNull final Observable<ActivityEvent> lifecycle) {
         
        return bind(lifecycle, ACTIVITY_LIFECYCLE);
    }
    
    @NonNull
    @CheckResult
    public static <T> LifecycleTransformer<T> bindFragment(@NonNull final Observable<FragmentEvent> lifecycle) {
         
        return bind(lifecycle, FRAGMENT_LIFECYCLE);
    }
    

    ACTIVITY_LIFECYCLE是:

    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");
                }
            }
        };
    

    FRAGMENT_LIFECYCLE是:

    private static final Function<FragmentEvent, FragmentEvent> FRAGMENT_LIFECYCLE =
        new Function<FragmentEvent, FragmentEvent>() {
         
            @Override
            public FragmentEvent apply(FragmentEvent lastEvent) throws Exception {
         
                switch (lastEvent) {
         
                    case ATTACH:
                        return FragmentEvent.DETACH;
                    case CREATE:
                        return FragmentEvent.DESTROY;
                    case CREATE_VIEW:
                        return FragmentEvent.DESTROY_VIEW;
                    case START:
                        return FragmentEvent.STOP;
                    case RESUME:
                        return FragmentEvent.PAUSE;
                    case PAUSE:
                        return FragmentEvent.STOP;
                    case STOP:
                        return FragmentEvent.DESTROY_VIEW;
                    case DESTROY_VIEW:
                        return FragmentEvent.DESTROY;
                    case DESTROY:
                        return FragmentEvent.DETACH;
                    case DETACH:
                        throw new OutsideLifecycleException("Cannot bind to Fragment lifecycle when outside of it.");
                    default:
                        throw new UnsupportedOperationException("Binding to " + lastEvent + " not yet implemented");
                }
            }
        };
    

    bind方法:

    @Nonnull
    @CheckReturnValue
    public static <T, R> LifecycleTransformer<T> bind(@Nonnull Observable<R> lifecycle,
                                                      @Nonnull final Function<R, R> correspondingEvents) {
         
        checkNotNull(lifecycle, "lifecycle == null");
        checkNotNull(correspondingEvents, "correspondingEvents == null");
        return bind(takeUntilCorrespondingEvent(lifecycle.share(), correspondingEvents));
    }
    
    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);
    }
    

    lifecycle.share()实际上调用的是其父类Observable的share方法:

    @CheckReturnValue
    @SchedulerSupport(SchedulerSupport.NONE)
    public final Observable<T> share() {
         
        return publish().refCount();
    }
    

    最终返回的是ObservableRefCount:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值