美文网首页Rx
RxSwift源码分析(17)——deallocating

RxSwift源码分析(17)——deallocating

作者: 无悔zero | 来源:发表于2020-11-05 17:45 被阅读0次

    在前面曾经探索过销毁流程和方式,其实还有一种方式:

    button.rx.tap
    .takeUntil(vc.rx.deallocating)
    .subscribe { (event) in
        print("页面释放时销毁序列")                
    }
    

    不过今天想分析的不是takeUntil,而是deallocatingdeallocating的探索过程会跟之前不太一样,先来看看例子:

    vc.rx.deallocating
    .subscribe { (event) in
        print("页面将要释放")                
    }
    
    1. 看看序列的创建,首先创建了DeallocatingProxy类,再返回序列(proxy.messageSent.asObservable()):
    vc.rx.deallocating
    
    extension Reactive where Base: AnyObject {
        ...
        public var deallocating: Observable<()> {
            return self.synchronized {
                do {
                    let proxy: DeallocatingProxy = try self.registerMessageInterceptor(deallocSelector)
                    return proxy.messageSent.asObservable()
                }
                catch let e {
                    return Observable.error(e)
                }
            }
        }
        
        fileprivate func registerMessageInterceptor<T: MessageInterceptorSubject>(_ selector: Selector) throws -> T {
            ...
            let targetImplementation = RX_ensure_observing(self.base, selector, &error)
            if targetImplementation == nil {
                throw error?.rxCocoaErrorForTarget(self.base) ?? RxCocoaError.unknown
            }
    
            subject.targetImplementation = targetImplementation!
    
            return subject
        }
    
    }
    
    1. registerMessageInterceptor函数的代码看上去有点复杂,重点在于RX_ensure_observing,内部竟然是OC代码:
    IMP __nullable RX_ensure_observing(id __nonnull target, SEL __nonnull selector, NSErrorParam error) {
        __block IMP targetImplementation = nil;
        @synchronized(target) {
            @synchronized([target class]) {
                [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) {
                    targetImplementation = [self ensurePrepared:target
                                                   forObserving:selector
                                                          error:error];
                }];
            }
        }
    
        return targetImplementation;
    }
    

    [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { }只是确保调用安全:

    1. 接着看block里调用的方法,这个方法的代码真的很多,只好直接找重点swizzleDeallocating
    @implementation RXObjCRuntime
    ...
    -(IMP __nullable)ensurePrepared:(id __nonnull)target forObserving:(SEL __nonnull)selector error:(NSErrorParam)error {
        ...
        if (selector == deallocSelector) {
            Class __nonnull deallocSwizzingTarget = [target class];
            IMP interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:deallocSwizzingTarget];
            if (interceptorIMPForSelector != nil) {
                return interceptorIMPForSelector;
            }
    
            if (![self swizzleDeallocating:deallocSwizzingTarget error:error]) {
                return nil;
            }
    
            interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:deallocSwizzingTarget];
            if (interceptorIMPForSelector != nil) {
                return interceptorIMPForSelector;
            }
        }
        ...
    }
    ...
    @end
    
    1. 看看swizzleDeallocating的实现,关键来了,转眼跳转到了宏,这写法就容易眼花了,得慢慢一一对应(我把参数一一分开,大家应该容易看懂点):
    @implementation RXObjCRuntime (InfrastructureMethods)
    ...
    SWIZZLE_INFRASTRUCTURE_METHOD(
        void,
        swizzleDeallocating,
        ,
        deallocSelector,
        DEALLOCATING_BODY
    )
    
    @end
    
    // infrastructure method
    
    #define NO_BODY(...)
    
    #define SWIZZLE_INFRASTRUCTURE_METHOD(
        return_value, 
        method_name, 
        parameters, 
        method_selector, 
        body, 
    ...
    )               \
    SWIZZLE_METHOD(
        return_value, 
        -(BOOL)method_name:(Class __nonnull)class parameters error:(NSErrorParam)error        \
            {                                                                                                              \
                SEL selector = method_selector; , //留意这里只是第二个参数
        body, 
        NO_BODY, 
        __VA_ARGS__
    )                                              \
    
    
    // common base
    
    #define SWIZZLE_METHOD(
        return_value, 
        method_prototype, 
        body, 
        invoked_body, 
        ...
    )                                          \
    method_prototype                                                                                                         \
        __unused SEL rxSelector = RX_selector(selector);                                                                     \
        IMP (^newImplementationGenerator)(void) = ^() {                                                                          \
        ...
        };                                                                                                                   \
                                                                                                                             \
        IMP (^replacementImplementationGenerator)(IMP) = ^(IMP originalImplementation) {                                     \
        ...
        };                                                                                                                   \
                                                                                                                             \
        return [self ensureSwizzledSelector:selector                                                                         \
                                    ofClass:class                                                                            \
                 newImplementationGenerator:newImplementationGenerator                                                       \
         replacementImplementationGenerator:replacementImplementationGenerator                                               \
                                      error:error];                                                                          \
     }                                                                                                                       \
    
    
    1. 最后发现宏的重点是通过调用ensureSwizzledSelector交换两个方法的IMP函数指针,实现ensureSwizzledSelector的代码也是很多,继续抓重点class_addMethod
    -(BOOL)ensureSwizzledSelector:(SEL __nonnull)selector
                          ofClass:(Class __nonnull)class
       newImplementationGenerator:(IMP(^)(void))newImplementationGenerator
    replacementImplementationGenerator:(IMP (^)(IMP originalImplementation))replacementImplementationGenerator
                            error:(NSErrorParam)error {
        ...
        IMP newImplementation = newImplementationGenerator();
    
        if (class_addMethod(class, selector, newImplementation, encoding)) {
            [self registerInterceptedSelector:selector implementation:newImplementation forClass:class];
    
            return YES;
        }
        ...
    }
    
    @end
    
    • 来到这里梳理一下思路,deallocating其实就是利用runtime交换方法来达到监听的目的。
    1. 这么一大圈才完成了DeallocatingProxy的创建流程,然后才是序列(proxy.messageSent.asObservable()):
    fileprivate final class DeallocatingProxy
        : MessageInterceptorSubject
        , RXDeallocatingObserver {
        ...
        let messageSent = ReplaySubject<()>.create(bufferSize: 1)
        ...
        @objc func deallocating() {
            self.messageSent.on(.next(()))
        }
    
        deinit {
            self.messageSent.on(.completed)
        }
    }
    

    接着可以看见DeallocatingProxydeallocating()函数会发送响应出去,根据RxSwift核心逻辑,最终来到外面的响应闭包:

    .subscribe { (event) in
        print("页面将要释放")                
    }
    
    1. 但是一直没看见deallocating()的调用,这里需要我们回顾一下上面的流程,因为它在这里调用了:
    #define DEALLOCATING_BODY(...)                                                        \
        id<RXDeallocatingObserver> observer = objc_getAssociatedObject(self, rxSelector); \
        if (observer != nil && observer.targetImplementation == thisIMP) {                \
            [observer deallocating];                                                      \
        }
    

    所以当监听的对象销毁时,便执行DeallocatingProxydeallocating()发送响应,最后DeallocatingProxy销毁时,便发送完成信号销毁序列。

    相关文章

      网友评论

        本文标题:RxSwift源码分析(17)——deallocating

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