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?
}
}
}
}