简体   繁体   中英

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). 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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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