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?
syncObjects
is implemented. – Lenz