Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between calling .cancel() on an AnyCancellable vs. making an AnyCancellable? = nil in SwiftUI?

I was playing around with Combine and I realised that instead of calling .cancel() on an AnyCancellable, making the AnyCancellable an Optional and setting it to nil also stops the stream of values.

Is setting an AnyCancellable? to nil instead of calling .cancel() on an AnyCancellable a bad thing? Does it have any negative consequences such as leaking memory or something?

For reference, this is the code:

class Test: ObservableObject {
    var canceller: AnyCancellable?
    
    func start() {
        let timerPublisher = Timer
            .publish(every: 1, on: .main, in: .common)
            .autoconnect()
        
        self.canceller = timerPublisher.sink { date in
            print("the date is \(date)")
        }
    }
    func stop1() {
        canceller?.cancel()
    }
    func stop2() {
        canceller = nil
    }
}
struct ContentView: View {
    @ObservedObject var test = Test()
    
    var body: some View {
        VStack(spacing: 20) {
            Button("Start") {
                self.test.start()
            }
            
            Button("Stop1") {
                self.test.stop1()  // Both buttons stop the stream of values
            }

            Button("Stop2") {
                self.test.stop2()  // Is there any difference between using this and stop1?
            }
        }
    }
}
like image 891
rayaantaneja Avatar asked Oct 28 '25 02:10

rayaantaneja


1 Answers

Is setting an AnyCancellable? to nil instead of calling .cancel() on an AnyCancellable a bad thing? Does it have any negative consequences such as leaking memory or something?

For cancelling both are equal, but from memory management perspective setting cancellable to nil is preferable, because after cancel() AnyCancellable itself remains alive, that might result in some unexpected side-effects, if owner continues to live and active and somehow refer to AnyCancellable property.

So, I'd say that for safety it is better to set AnyCancellable to nil - this does both things.

like image 120
Asperi Avatar answered Oct 29 '25 18:10

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!