Reputation: 1274
As the title, is it necessary to call disposed(by:)
in any case? If yes, why?
Consider a simple example like this:
class ViewController: UIViewController {
let button = UIButton()
override func viewDidLoad() {
button.rx.tap.bind(onNext: { _ in
print("Button tapped!")
})
// Does this make any retain cycle here?
}
}
Upvotes: 3
Views: 1272
Reputation: 33967
No, it is not necessary to call .disposed(by:)
in every case.
If you have an Observable that you know will eventually send a stop event, and you know that you want to keep listening to that observable until it does so, then there is no reason/need to dispose the subscription and therefore no need to insert the disposable into a dispose bag.
The reason .subscribe
and its ilk return a Disposable is so that the calling code can end the subscription before the observable has completed. The calling code ends the subscription by calling dispose()
on the disposable returned. Otherwise, the subscription will continue until the source observable sends a stop event (either completed or error.)
If the calling code doesn't dispose the subscription, and the source observable doesn't send a stop event, then the subscription will continue to operate even if all other code involved has lost all references to the objects involved in the subscription.
So for example, if you put this in a viewDidLoad:
_ = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
.subscribe(onNext: { print($0) })
The code above will continue to print values long after the view controller that created it ceases to exist.
In the example you presented, the UIButton object will emit a completed event when it is deinitialized, so if you want to listen to the button right up until that happens, putting the disposable in a dispose bag isn't necessary.
Ignoring disposables means you need to be very cognizant as to which Observables complete and which ones don't, but if you have that understanding, you can ignore them. Just remember that the next developer down the line, or future you, won't have as good an understanding of the code as you do.
Upvotes: 5