Adapted from https://gist.github.com/filimo/6f826b352f75cd1640e4e705340c0301
Instead of using a Set
, use a CancelBag
instead (kind of like the DisposeBag
in RxSwift).
No need to use references when storing cancellables and you can also collect multiple cancellable instances without calling .store(in:)
.
Before:
let subscriptions = Set<AnyCancellable>()
optionalPublisher?
.sink { value in
print("received value: \(value)")
}
.store(in: &subscriptions)
publisher
.assign(to: \.someVar, on: self)
.store(in: &subscriptions)
subject
.subscribe(publisher2)
.store(in: &subscriptions)
Now:
let cancelBag = CancelBag()
optionalPublisher?
.sink { value in
print("received value: \(value)")
}
.store(in: cancelBag)
publisher
.assign(to: \.someVar, on: self)
.store(in: cancelBag)
subject
.subscribe(publisher2)
.store(in: cancelBag)
Or even better:
let cancelBag = CancelBag()
cancelBag.collect {
optionalPublisher?
.sink { value in
print("received value: \(value)")
}
publisher
.assign(to: \.someVar, on: self)
subject
.subscribe(publisher2)
}
It's as simple as:
cancelBag.cancel()