gpt4 book ai didi

swift - RxSwift 为什么我们在不调用 dispose 的情况下会发生内存泄漏

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:23 25 4
gpt4 key购买 nike

我正在阅读有关 RxSwift 的文章,并且有很多关于内存泄漏的讨论。这里引用了主要 RxSwift 的入门指南 repo :

If a sequence does not terminate on its own, such as with a series of button taps, resources will be allocated permanently unless dispose is called manually, automatically inside of a disposeBag, with the takeUntil operator, or in some other way.

这是 Reactive Programming with Swift第 2 章:Observables 中的一段代码内存泄漏的地方:

Observable<String>.create({ observer in
observer.onNext("1")
// observer.onError(MyError.anError)
// observer.onCompleted()
return Disposables.create()
}).subscribe(
onNext: { print($0) },
onError: { print($0) },
onCompleted: { print("Completed") },
onDisposed: { print("Disposed") }
)

我知道处置资源非常重要(例如,处置袋)。但是,我不明白的是:哪些资源在泄漏以及如何泄漏?

最佳答案

它会泄漏,因为它捕获的链和所有资源都不会被释放。

RxSwift 分配一些对象,这些对象构成了您订阅的链。它们都占用内存,并且对于您的 Observable 链的正确业务逻辑是必需的。您还可以将一些超出范围的对象传递给链中的闭包,并且它们也将被保留,因为闭包是一种引用类型并且强烈保留它们捕获的资源。

关于swift - RxSwift 为什么我们在不调用 dispose 的情况下会发生内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com