Created
June 27, 2019 05:07
-
-
Save iamchiwon/2bf9f8efc616cdce93de375be370afdb to your computer and use it in GitHub Desktop.
CancelBag for combine framework that works like DisposeBag of RxSwift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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