简体   繁体   English

DispatchQueue.main.async 如何存储它的块

[英]How does DispatchQueue.main.async store it's blocks

I have a code similar to this:我有一个类似的代码:

func fetchBalances() -> Observable<Result<[User], Error>> {

    Observable.create { observer in
        
        var dataChangeDisposable: Disposable?
        DispatchQueue.main.async {

            let realm = try! Realm()
            let user = realm.objects(UserData.self)
            dataChangeDisposable = Observable.collection(from: user)
                .map { $0.map { UserData.convert($0) } }
                .subscribe(onNext: {
                    observer.onNext(.success($0))
                })
        }

        return Disposables.create {
            dataChangeDisposable?.dispose()
        }
    }
}

I need to use some thread with run loop in order to maintain subscription to Realm database (Realm's restriction).我需要使用一些带有运行循环的线程来维护对 Realm 数据库的订阅(Realm 的限制)。 For now I'm using DispatchQueue.main.async {} method and I noticed that subscription remains active all the time, how does DispatchQueue.main stores it's submitted blocks and if Observable destroys does it mean that I'm leaking blocks in memory?现在我正在使用 DispatchQueue.main.async {} 方法,我注意到订阅一直保持活动状态,DispatchQueue.main 如何存储它提交的块,如果 Observable 销毁是否意味着我在内存中泄漏块?

The block sent to the dispatch queue is deleted immediately after execution.发送到调度队列的块在执行后立即被删除。 It isn't stored for very long at all.它根本不会存储很长时间。

If your subscription "remains active all the time" then it's because it's not being disposed of properly.如果您的订阅“一直有效”,那是因为它没有被正确处理。 Likely what is happening here is that the block sent to Disposables.create is being called before dataChangeDisposable contains a value.可能这里发生的事情是发送到Disposables.create的块在dataChangeDisposable包含值之前被调用。

Test my hypothesis by changing the code to:通过将代码更改为以下内容来测试我的假设:

return Disposables.create {
    dataChangeDisposable!.dispose()
}

If your app crashes because dataChangeDisposable is nil, then that's your problem.如果您的应用程序因为dataChangeDisposable为零而崩溃,那么这就是您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM