Created
April 28, 2020 11:54
-
-
Save CassiusPacheco/18cdabd50d19e2d1180fedae2a070d31 to your computer and use it in GitHub Desktop.
A dispose bag that keeps only one disposable in the bag at a time.
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
import Foundation | |
import RxSwift | |
extension Disposable { | |
/// Adds `self` to `single` | |
/// | |
/// - parameter single: `SingleDisposer` to add `self` to. | |
/// - note: `SingleDisposer` is a wrapper of `DisposeBag` that is recreated | |
/// whenever a disposable object is inserted into it, cancelling any | |
/// previous subscriptions. It keeps at most one subscription at a | |
/// time in memory. | |
/// `SingleDisposer` releases subscriptions on deinit. | |
public func disposed(by single: SingleDisposer) { | |
single.insert(self) | |
} | |
} | |
/// `SingleDisposer` is a wrapper of `DisposeBag` that is recreated | |
/// whenever a disposable object is inserted into it, cancelling any | |
/// previous subscription. It keeps at most one subscription at a | |
/// time in memory. | |
/// `SingleDisposer` releases subscriptions on deinit. | |
public final class SingleDisposer: Disposable { | |
private var bag: DisposeBag? | |
public init() {} | |
/// Dispose current subscription. | |
public func dispose() { | |
bag = nil | |
} | |
/// Cancels any previous subscription before inserting the new one | |
/// into the disposer bag. | |
public func insert(_ disposable: Disposable) { | |
bag = DisposeBag() | |
bag?.insert(disposable) | |
} | |
deinit { | |
dispose() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment