In Combine, an AnyCancellable is a type that represents a subscription which you can cancel. When you subscribe to a publisher, it returns an AnyCancellable that, when deinitialized or explicitly canceled, terminates the subscription.
Why Use Set<AnyCancellable>?
Automatic Cancellation: By storing your AnyCancellable objects in a collection (commonly a Set), they stay in memory as long as you need the subscription. When the collection is deallocated (for example, when a view controller is dismissed), each AnyCancellable in the set is cancelled automatically.
Unordered Collection with Unique Elements: A Set is unordered and ensures that you don’t have duplicates. This aligns well with the nature of subscriptions where the order typically doesn’t matter and you don’t want multiple identical cancellation tokens.
Convenient API: The insert(_:) method on a Set gives you a neat way to add new subscriptions without worrying about the index, and it handles the uniqueness for you.
Can You Use [AnyCancellable] Instead?
You can use an array ([AnyCancellable]) to store your subscriptions, but there are a few reasons why a Set is generally preferred:
Order Doesn’t Matter: Subscriptions are typically not order-dependent, so an unordered collection like a Set is an ideal fit.
Handling Duplicates: A Set automatically prevents duplicate subscriptions from being stored, whereas with an array you’d have to manually manage this if it matters for your use case.
API Convention: The Combine community and Apple’s examples typically use a Set<AnyCancellable>, so following this convention can make your code more familiar to other developers.
Example
Here's a typical usage with a Set<AnyCancellable>:
swift
import Combine
class MyViewModel {
private var cancellables = Set<AnyCancellable>()
func start() {
let publisher = [1, 2, 3].publisher
publisher
.sink { value in
print("Received \(value)")
}
.store(in: &cancellables)
}
}
In this example, the subscription is stored in the cancellables set. When MyViewModel is deallocated, all subscriptions in the set will be automatically cancelled.
Conclusion
While you could use [AnyCancellable] instead of Set<AnyCancellable>, the Set is generally preferred in Combine for managing the lifecycle of subscriptions due to its built-in handling of uniqueness and its alignment with the unordered nature of subscriptions.