-
Notifications
You must be signed in to change notification settings - Fork 431
/
Copy pathDisposable.swift
396 lines (345 loc) · 10.1 KB
/
Disposable.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
//
// Disposable.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-06-02.
// Copyright (c) 2014 GitHub. All rights reserved.
//
/// Represents something that can be “disposed”, usually associated with freeing
/// resources or canceling work.
public protocol Disposable: AnyObject {
/// Whether this disposable has been disposed already.
var isDisposed: Bool { get }
/// Disposing of the resources represented by `self`. If `self` has already
/// been disposed of, it does nothing.
///
/// - note: Implementations must issue a memory barrier.
func dispose()
}
/// Represents the state of a disposable.
private enum DisposableState: Int32 {
/// The disposable is active.
case active
/// The disposable has been disposed.
case disposed
}
extension UnsafeAtomicState where State == DisposableState {
/// Try to transition from `active` to `disposed`.
///
/// - returns: `true` if the transition succeeds. `false` otherwise.
@inline(__always)
fileprivate func tryDispose() -> Bool {
return tryTransition(from: .active, to: .disposed)
}
}
/// A disposable that does not have side effect upon disposal.
internal final class _SimpleDisposable: Disposable {
private let state = UnsafeAtomicState<DisposableState>(.active)
var isDisposed: Bool {
return state.is(.disposed)
}
func dispose() {
_ = state.tryDispose()
}
deinit {
state.deinitialize()
}
}
/// A disposable that has already been disposed.
internal final class NopDisposable: Disposable {
static let shared = NopDisposable()
var isDisposed = true
func dispose() {}
private init() {}
}
/// A type-erased disposable that forwards operations to an underlying disposable.
public final class AnyDisposable: Disposable {
private final class ActionDisposable: Disposable {
let state: UnsafeAtomicState<DisposableState>
var action: (() -> Void)?
var isDisposed: Bool {
return state.is(.disposed)
}
init(_ action: (() -> Void)?) {
self.state = UnsafeAtomicState(.active)
self.action = action
}
deinit {
state.deinitialize()
}
func dispose() {
if state.tryDispose() {
action?()
action = nil
}
}
}
private let base: Disposable
public var isDisposed: Bool {
return base.isDisposed
}
/// Create a disposable which runs the given action upon disposal.
///
/// - parameters:
/// - action: A closure to run when calling `dispose()`.
public init(_ action: @escaping () -> Void) {
base = ActionDisposable(action)
}
/// Create a disposable.
public init() {
base = _SimpleDisposable()
}
/// Create a disposable which wraps the given disposable.
///
/// - parameters:
/// - disposable: The disposable to be wrapped.
public init(_ disposable: Disposable) {
base = disposable
}
public func dispose() {
base.dispose()
}
}
/// A disposable that will dispose of any number of other disposables.
public final class CompositeDisposable: Disposable {
private let disposables: Atomic<Bag<Disposable>?>
private var state: UnsafeAtomicState<DisposableState>
public var isDisposed: Bool {
return state.is(.disposed)
}
/// Initialize a `CompositeDisposable` containing the given sequence of
/// disposables.
///
/// - parameters:
/// - disposables: A collection of objects conforming to the `Disposable`
/// protocol
public init<S: Sequence>(_ disposables: S) where S.Iterator.Element == Disposable {
let bag = Bag(disposables)
self.disposables = Atomic(bag)
self.state = UnsafeAtomicState(.active)
}
/// Initialize a `CompositeDisposable` containing the given sequence of
/// disposables.
///
/// - parameters:
/// - disposables: A collection of objects conforming to the `Disposable`
/// protocol
public convenience init<S: Sequence>(_ disposables: S)
where S.Iterator.Element == Disposable?
{
self.init(disposables.compactMap { $0 })
}
/// Initializes an empty `CompositeDisposable`.
public convenience init() {
self.init([Disposable]())
}
public func dispose() {
if state.tryDispose(), let disposables = disposables.swap(nil) {
for disposable in disposables {
disposable.dispose()
}
}
}
/// Add the given disposable to the composite.
///
/// - parameters:
/// - disposable: A disposable.
///
/// - returns: A disposable to remove `disposable` from the composite. `nil` if the
/// composite has been disposed of, `disposable` has been disposed of, or
/// `disposable` is `nil`.
@discardableResult
public func add(_ disposable: Disposable?) -> Disposable? {
guard let d = disposable, !d.isDisposed, !isDisposed else {
disposable?.dispose()
return nil
}
return disposables.modify { disposables in
guard let token = disposables?.insert(d) else { return nil }
return AnyDisposable { [weak self] in
self?.disposables.modify {
$0?.remove(using: token)
}
}
}
}
/// Add the given action to the composite.
///
/// - parameters:
/// - action: A closure to be invoked when the composite is disposed of.
///
/// - returns: A disposable to remove `disposable` from the composite. `nil` if the
/// composite has been disposed of, `disposable` has been disposed of, or
/// `disposable` is `nil`.
@discardableResult
public func add(_ action: @escaping () -> Void) -> Disposable? {
return add(AnyDisposable(action))
}
deinit {
state.deinitialize()
}
/// Adds the right-hand-side disposable to the left-hand-side
/// `CompositeDisposable`.
///
/// ````
/// disposable += producer
/// .filter { ... }
/// .map { ... }
/// .start(observer)
/// ````
///
/// - parameters:
/// - lhs: Disposable to add to.
/// - rhs: Disposable to add.
///
/// - returns: An instance of `DisposableHandle` that can be used to opaquely
/// remove the disposable later (if desired).
@discardableResult
public static func += (lhs: CompositeDisposable, rhs: Disposable?) -> Disposable? {
return lhs.add(rhs)
}
/// Adds the right-hand-side `ActionDisposable` to the left-hand-side
/// `CompositeDisposable`.
///
/// ````
/// disposable += { ... }
/// ````
///
/// - parameters:
/// - lhs: Disposable to add to.
/// - rhs: Closure to add as a disposable.
///
/// - returns: An instance of `DisposableHandle` that can be used to opaquely
/// remove the disposable later (if desired).
@discardableResult
public static func += (lhs: CompositeDisposable, rhs: @escaping () -> Void) -> Disposable? {
return lhs.add(rhs)
}
}
/// A disposable that, upon deinitialization, will automatically dispose of
/// its inner disposable.
public final class ScopedDisposable<Inner: Disposable>: Disposable {
/// The disposable which will be disposed when the ScopedDisposable
/// deinitializes.
public let inner: Inner
public var isDisposed: Bool {
return inner.isDisposed
}
/// Initialize the receiver to dispose of the argument upon
/// deinitialization.
///
/// - parameters:
/// - disposable: A disposable to dispose of when deinitializing.
public init(_ disposable: Inner) {
inner = disposable
}
deinit {
dispose()
}
public func dispose() {
return inner.dispose()
}
}
extension ScopedDisposable where Inner == AnyDisposable {
/// Initialize the receiver to dispose of the argument upon
/// deinitialization.
///
/// - parameters:
/// - disposable: A disposable to dispose of when deinitializing, which
/// will be wrapped in an `AnyDisposable`.
public convenience init(_ disposable: Disposable) {
self.init(Inner(disposable))
}
}
extension ScopedDisposable where Inner == CompositeDisposable {
/// Adds the right-hand-side disposable to the left-hand-side
/// `ScopedDisposable<CompositeDisposable>`.
///
/// ````
/// disposable += { ... }
/// ````
///
/// - parameters:
/// - lhs: Disposable to add to.
/// - rhs: Disposable to add.
///
/// - returns: An instance of `DisposableHandle` that can be used to opaquely
/// remove the disposable later (if desired).
@discardableResult
public static func += (lhs: ScopedDisposable<CompositeDisposable>, rhs: Disposable?) -> Disposable? {
return lhs.inner.add(rhs)
}
/// Adds the right-hand-side disposable to the left-hand-side
/// `ScopedDisposable<CompositeDisposable>`.
///
/// ````
/// disposable += { ... }
/// ````
///
/// - parameters:
/// - lhs: Disposable to add to.
/// - rhs: Closure to add as a disposable.
///
/// - returns: An instance of `DisposableHandle` that can be used to opaquely
/// remove the disposable later (if desired).
@discardableResult
public static func += (lhs: ScopedDisposable<CompositeDisposable>, rhs: @escaping () -> Void) -> Disposable? {
return lhs.inner.add(rhs)
}
}
/// A disposable that disposes of its wrapped disposable, and allows its
/// wrapped disposable to be replaced.
public final class SerialDisposable: Disposable {
private let _inner: Atomic<Disposable?>
private var state: UnsafeAtomicState<DisposableState>
public var isDisposed: Bool {
return state.is(.disposed)
}
/// The current inner disposable to dispose of.
///
/// Whenever this property is set (even to the same value!), the previous
/// disposable is automatically disposed.
public var inner: Disposable? {
get {
return _inner.value
}
set(disposable) {
_inner.swap(disposable)?.dispose()
if let disposable = disposable, isDisposed {
disposable.dispose()
}
}
}
/// Initializes the receiver to dispose of the argument when the
/// SerialDisposable is disposed.
///
/// - parameters:
/// - disposable: Optional disposable.
public init(_ disposable: Disposable? = nil) {
self._inner = Atomic(disposable)
self.state = UnsafeAtomicState(DisposableState.active)
}
public func dispose() {
if state.tryDispose() {
_inner.swap(nil)?.dispose()
}
}
deinit {
state.deinitialize()
}
}
extension ScopedDisposable where Inner == SerialDisposable {
/// The current inner disposable of the `SerialDisposable` wrapped
/// in the `ScopedDisposable` to dispose of.
///
/// Whenever this property is set (even to the same value!), the previous
/// disposable is automatically disposed.
public var inner: Disposable? {
get {
return inner.inner
}
set {
inner.inner = newValue
}
}
}