Skip to content

Instantly share code, notes, and snippets.

@iamchiwon
Created June 27, 2019 05:07
Show Gist options
  • Select an option

  • Save iamchiwon/2bf9f8efc616cdce93de375be370afdb to your computer and use it in GitHub Desktop.

Select an option

Save iamchiwon/2bf9f8efc616cdce93de375be370afdb to your computer and use it in GitHub Desktop.
CancelBag for combine framework that works like DisposeBag of RxSwift
class CancelBag {
private var bag: [Cancellable] = []
private var named: [String: Cancellable] = [:]
func cancelAll() {
bag.forEach { $0.cancel() }
bag = []
named.forEach { $0.value.cancel() }
named = [:]
}
func cancel(_ name: String) {
named[name]?.cancel()
}
func add(_ cancellable: Cancellable, as name: String) {
named[name] = cancellable
}
func add(_ cancellable: Cancellable, as name: String? = nil) {
if let name = name {
named[name] = cancellable
} else {
bag.append(cancellable)
}
}
deinit {
cancelAll()
}
}
extension Cancellable {
func add(to bag: CancelBag) {
bag.add(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment