I have ViewModel with disposable Set defined this way
class ViewModel {
private var disposables = Set<AnyCancellable>()
func sync() {
repo.syncObjects()
.handleEvents(receiveCancel: {
print("Synced objects: CANCELED!")
})
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
print("Synced objects: \(error)")
case .finished:
print("Synced objects: finished")
}
}) { objects in
print("Synced objects: \(objects)")
}.store(in: &disposables)
}
deinit { print("ViewModel deinit") }
}
I am calling sync() in onAppear in SwiftUI view. Then I am fast switching screens and ViewModel referenced from SwiftUI view is deallocated by ARC like deinit is called but subscriptions seems to remain alive and disposable reference does not cancel subscription it fetches data from Network and saved them in Core Data and prints Synced objects: objects, Synced objects: finished. And keeps being alive even when I stop switching screens for several seconds to complete old requests.
Should I manually cancel AnyCancellable? shouldn't it be cancelled automagically?
No, you dont need to cancel any cancellable because this kind of object calls the method cancel
when deinitialized. So your code is correct.
Apple's documentation of AnyCancellable:
An AnyCancellable instance automatically calls
cancel()
when deinitializedhttps://developer.apple.com/documentation/combine/anycancellable