Guest User

Untitled

a guest
Mar 24th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import RxSwift
  2.  
  3. public final class DisposeCache<Key>
  4. : ExpressibleByDictionaryLiteral where Key : Hashable {
  5. ///
  6. private var lock = NSRecursiveLock()
  7.  
  8. ///
  9. private var storage: [Key: Disposable]
  10.  
  11. ///
  12. private var isDisposed = false
  13.  
  14. ///
  15. public var isEmpty: Bool {
  16. return storage.isEmpty
  17. }
  18.  
  19. ///
  20. public var count: Int {
  21. return storage.count
  22. }
  23.  
  24. ///
  25. public init() {
  26. storage = [:]
  27. }
  28.  
  29. ///
  30. public init(dictionaryLiteral elements: (Key, Disposable)...) {
  31. storage = Dictionary(uniqueKeysWithValues: elements)
  32. }
  33.  
  34. ///
  35. public init<S>(
  36. uniqueKeysWithDisposables keysAndDisposables: S
  37. ) where S : Sequence, S.Element == (Key, Disposable) {
  38. storage = Dictionary(uniqueKeysWithValues: keysAndDisposables)
  39. }
  40.  
  41. ///
  42. deinit { dispose() }
  43. }
  44.  
  45. extension DisposeCache {
  46. ///
  47. public subscript (_ key: Key) -> Disposable? {
  48. get { return storage[key] }
  49. set { assign(newValue, to: key)?.dispose() }
  50. }
  51.  
  52. ///
  53. public func contains(_ key: Key) -> Bool {
  54. return storage[key] != nil
  55. }
  56.  
  57. ///
  58. public func remove(_ key: Key) {
  59. self[key] = nil
  60. }
  61. }
  62.  
  63. extension DisposeCache {
  64. ///
  65. private func assign(_ disposable: Disposable?, to key: Key) -> Disposable? {
  66. lock.lock()
  67. defer { lock.unlock() }
  68. if isDisposed {
  69. return disposable
  70. }
  71. let oldDisposable = storage[key]
  72. storage[key] = disposable
  73. return oldDisposable
  74. }
  75.  
  76. ///
  77. private func dispose() {
  78. lock.lock()
  79. defer { lock.unlock() }
  80. let disposables = storage.map { $0.value }
  81. storage.removeAll(keepingCapacity: false)
  82. isDisposed = true
  83. disposables.forEach { $0.dispose() }
  84. }
  85. }
  86.  
  87. extension Disposable {
  88. ///
  89. public func disposed<Key>(by cache: DisposeCache<Key>, key: Key) {
  90. cache[key] = self
  91. }
  92. }
Add Comment
Please, Sign In to add comment