rx-swift

How does the `dispose()` method in RxSwift work?


I have a question about memory management in RxSwift.

I understand that when we create an Observable and an Observer subscribes to it, the Observable and the Disposable are strongly referencing each other. To resolve this, we use a DisposeBag or call the dispose() method of the Disposable to release memory.

However, when the ViewController is deallocated, followed by the deallocation of the DisposeBag, and subsequently the Disposablesarray, how is the strong reference cycle between Disposables and Observables resolved?

Is there a specific mechanism that breaks the cycle when the dispose() method is called? Where can I find the supporting code for this functionality?

Thank you!


Solution

  • I understand that when we create an Observable and an Observer subscribes to it, the Observable and the Disposable are strongly referencing each other.

    This is incorrect. The Observable does not reference the Disposable at all. The Disposable references itself and will hold that reference until either its dispose() is called or the observable emits a stop event (completed or error).

    The only reason to store the disposable in a dispose bag is to ensure that dispose is called when the bag is deleted. You can freely ignore disposables if you know you want the chain to continue until the source observable stops.