Rx

RxSwift源码分析(20)——内存管理

2020-11-10  本文已影响0人  无悔zero

之前在探索RxSwift源码的时候,发现几个地方都有循环引用,但那是故意的,而我们使用RxSwift的时候,如果循环引用就不好说故意了。那现在根据RxSwift核心逻辑销毁流程的探索,把RxSwift的引用关系捋一捋:

1. Observable<Any>.create{ self }
self.observable = Observable<Any>.create { (anyObserver) -> Disposable in
    print(self)  //循环引用1
    anyObserver.onNext("保存了observable")
    anyObserver.onCompleted()
    return Disposables.create()
}
let observable = Observable<Any>.create { (anyObserver) -> Disposable in
    print(self)  //没有循环引用
    anyObserver.onNext("不保存observable")
    anyObserver.onCompleted()
    return Disposables.create()
}
2. observable.subscribe { self }
let observable = Observable<Any>.create { (anyObserver) -> Disposable in
    anyObserver.onNext("没有使用weak")
    anyObserver.onCompleted()
    return Disposables.create()
}
let dispose = observable.subscribe { (text) in
    print(self)  //循环引用2
}
dispose.disposed(by: self.disposbag)
let observable = Observable<Any>.create { (anyObserver) -> Disposable in
    anyObserver.onNext("使用weak修饰")
    anyObserver.onCompleted()
    return Disposables.create()
}
let dispose = observable.subscribe {[weak self] (text) in
    print(self)  //没有循环引用
}
dispose.disposed(by: self.disposbag)
3. Disposables.create{ self }
第一种情况
self.observable = Observable<Any>.create { (anyObserver) -> Disposable in
    anyObserver.onNext("保存了observable")
    anyObserver.onCompleted()
    return Disposables.create{
        print(self)  //循环引用
    }
}
let observable = Observable<Any>.create { (anyObserver) -> Disposable in
    anyObserver.onNext("没有保存observable")
    anyObserver.onCompleted()
    return Disposables.create{
        print(self)  //没有循环引用
    }
}
self.observable = Observable<Any>.create {[weak self] (anyObserver) -> Disposable in
    anyObserver.onNext("使用weak修饰")
    anyObserver.onCompleted()
    return Disposables.create{
        print(self)  //没有循环引用
    }
}
第二种情况
let observable = Observable<Any>.create { (anyObserver) -> Disposable in
    anyObserver.onNext("不发送完成事件")
    return Disposables.create{
        print(self)  //循环引用
    }
}
let dispose = observable.subscribe { (text) in
    print("收到响应")
}
dispose.disposed(by: self.disposbag)
let observable = Observable<Any>.create { (anyObserver) -> Disposable in
    anyObserver.onNext("发送完成事件")
    anyObserver.onCompleted()
    return Disposables.create{
        print(self)  //没有循环引用
    }
}
let dispose = observable.subscribe { (text) in
    print("收到响应")
}
dispose.disposed(by: self.disposbag)
补充

使用之前,需要先在podfile上添加并执行pod install:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == 'RxSwift'
      target.build_configurations.each do |config|
        if config.name == 'Debug'
          config.build_settings['OTHER_SWIFT_FLAGS'] ||= ['-D', 'TRACE_RESOURCES']
        end
      end
    end
  end
end

接着直接获取现有计数,来判断是否释放完全,如果释放完全计数为0:

RxSwift.Resources.total
上一篇下一篇

猜你喜欢

热点阅读