RxSwiftCommunity / RxCoreData

RxSwift extensions for Core Data
MIT License
164 stars 68 forks source link

Does keeping a reference to Observer cause a retain-cycle? #39

Closed isidorebaldado closed 6 years ago

isidorebaldado commented 6 years ago

I'm still getting familiar with RxSwift, especially with regards to its memory management. I'm not clear on "what" the observer is. So in FetchedResultsControllerEntityObserver, it keeps a reference to observer so it can send onNext events in the delegate methods. Is this not a retain cycle, because observer is being held by the FetchedResultsControllerEntityObserver and also (I might be wrong here) by the Observable it's created in? Or is this one of those scenarios where all the references are being held "down-stream" so you don't really have a parent<--> child retain-cycle, just two references to a child.

In the Observable.create( (observer) -> Disposable) call, who "owns" the observer?

marshallxxx commented 6 years ago

No, in this case there is no retain cycle.

Observable.create { observer in

            let observerAdapter = FetchedResultsControllerEntityObserver(observer: observer, fetchRequest: fetchRequest, managedObjectContext: self.base, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName)

            return Disposables.create {
                observerAdapter.dispose()
            }
        }

Observer is retained by Observable and FetchedResultsControllerEntityObserver FetchedResultsControllerEntityObserver is retained by Observable, it has a reference in Disposable As soon as Observable will be deallocated, FetchedResultsControllerEntityObserver will have no other reference which will release it. Then Observer will be released as well.

isidorebaldado commented 6 years ago

Oh, so the Observable owns the Observer. And FetchedResultsControllerEntityObserver is also owned by the Observable, so it's all down stream and will be deallocated with Observable. That makes a lot of sense. Thank you for your explanation.