Skip to content

Instantly share code, notes, and snippets.

@CassiusPacheco
Created April 28, 2020 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CassiusPacheco/18cdabd50d19e2d1180fedae2a070d31 to your computer and use it in GitHub Desktop.
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.
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