Skip to content
This repository has been archived by the owner on Jan 24, 2023. It is now read-only.

Commit

Permalink
Merge pull request #161 from UrbanCompass/tim/revert
Browse files Browse the repository at this point in the history
Revert "Dispose on deinit"
  • Loading branch information
tim-chamberlin authored May 29, 2021
2 parents 00b51c4 + 7ec7445 commit 678d653
Show file tree
Hide file tree
Showing 14 changed files with 148 additions and 195 deletions.
36 changes: 23 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,24 +44,14 @@ let observable = Observable<thing>()
```

## Disposer
### What the Disposer IS

The disposer is used to maintain reference to many subscriptions in a single location. When a disposer is deinitialized, it removes all of its referenced subscriptions from memory. A disposer is usually located in a centralized place where most of the subscriptions happen (ie: UIViewController in an MVVM architecture). Since most of the subscriptions are to different observables, and those observables are tied to type, all the things that are going to be disposed need to comform to `Disposable`.
A disposer is in charge of removing all the subscriptions. A disposer is usually located in a centralized place where most of the subscriptions happen (ie: UIViewController in an MVVM architecture). Since most of the subscriptions are to different observables, and those observables are tied to type, all the things that are going to be disposed need to comform to `Disposable`.

### What the Disposer IS NOT

The disposer is not meant to prevent retain cycles. A common example is a `UIViewController` that has reference to a `Disposer` object. A subscription definition might look something like this:
If the `Disposer` helps get rid of the closures and prevent retention cycles (see weak self section). For the sake of all the examples, let's have a disposer created:

```swift
extension MyViewController {
button.tap.subscribe(onNext: { [weak self] in
self?.navigationController.push(newVc)
}).add(to: disposer)
}
let disposer = Disposer()
```
Without specifying a `[weak self]` capture list in a scenario like this, a retain cycle is created between the subscriber and the view controller. In this example, without the capture list, the view controller will not be deallocated as expected, causing its disposer object to stay in memory as well. Since the `Disposer` removes its referenced subscribers when it is deinitialized, these subscribers will stay in memory as well.

See [https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html](https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html) for more details on memory management in Swift.

## Closure Wrapper

Expand Down Expand Up @@ -229,6 +219,26 @@ observable.subscribe(queue: .main,
).add(to: disposer)
```

## Weak self is optional

You can use `[weak self]` if you want, but with the introduction of `Disposer`, retention cycles are destroyed when calling `disposer.disposeAll()`.

One idea would be to call `disposer.disposeAll()` when you pop a view controller from the navigation stack.

```swift
protocol HasDisposer {
var disposer: Disposer
}

class NavigationController: UINavigationController {
public override func popViewController(animated: Bool) -> UIViewController? {
let viewController = super.popViewController(animated: animated)
(viewController as? HasDisposer).disposer.disposeAll()
return viewController
}
}
```

# In Practice

## Subscribing to Notifications
Expand Down
4 changes: 0 additions & 4 deletions Snail/Closure.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,6 @@ public class Closure<T>: DisposableType {
self.closure = closure
}

deinit {
dispose()
}

public func dispose() {
closure = nil
}
Expand Down
15 changes: 3 additions & 12 deletions Snail/Disposer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,15 @@ public protocol DisposableType {

public class Disposer {
private(set) public var disposables: [DisposableType] = []
private let disposablesQueue = DispatchQueue(label: "snail-disposer-queue", attributes: .concurrent)

public init() {}

deinit {
disposeAll()
}

public func disposeAll() {
disposablesQueue.sync {
self.disposables.forEach { $0.dispose() }
self.disposables.removeAll()
}
disposables.forEach { $0.dispose() }
disposables.removeAll()
}

public func add(disposable: DisposableType) {
disposablesQueue.sync {
self.disposables.append(disposable)
}
disposables.append(disposable)
}
}
5 changes: 1 addition & 4 deletions Snail/Extensions/UIViewExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public extension UIView {

let tap = UITapGestureRecognizer()
addGestureRecognizer(tap)
tap.asObservable().subscribe(onNext: { [weak observable] _ in observable?.on(.next(())) }).add(to: disposer)
tap.asObservable().subscribe(onNext: { [weak observable] _ in observable?.on(.next(())) })

return observable
}
Expand All @@ -41,16 +41,13 @@ public extension UIView {
}
observable.on(.next((offset.cgRectValue.size.height, duration)))
})
.add(to: disposer)

observe(event: UIResponder.keyboardWillHideNotification).subscribe(onNext: { notification in
guard let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else {
return
}
observable.on(.next((0, duration)))
})
.add(to: disposer)

return observable
}

Expand Down
15 changes: 0 additions & 15 deletions Snail/Extensions/URLSessionExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,6 @@ extension URLSession {
}
}

private static var disposerKey = "com.compass.Snail.URLSession.Disposer"

public var disposer: Disposer {
if let disposer = objc_getAssociatedObject(self, &URLSession.disposerKey) as? Disposer {
return disposer
}
let disposer = Disposer()
objc_setAssociatedObject(self, &URLSession.disposerKey, disposer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return disposer
}

public func decoded<T: Codable>(request: URLRequest) -> Observable<(T, URLResponse)> {
let observer = Replay<(T, URLResponse)>(1)
data(request: request).subscribe(onNext: { data, response in
Expand All @@ -39,7 +28,6 @@ extension URLSession {
}
observer.on(.next((codedObject, response)))
}, onError: { observer.on(.error($0)) })
.add(to: disposer)
return observer
}

Expand All @@ -52,7 +40,6 @@ extension URLSession {
}
observer.on(.next((dictionary, response)))
}, onError: { observer.on(.error($0)) })
.add(to: disposer)
return observer
}

Expand All @@ -65,7 +52,6 @@ extension URLSession {
}
observer.on(.next((dictionary, response)))
}, onError: { observer.on(.error($0)) })
.add(to: disposer)
return observer
}

Expand Down Expand Up @@ -101,7 +87,6 @@ extension URLSession {
observer.on(.next((image, response)))
observer.on(.done)
}, onError: { observer.on(.error($0)) })
.add(to: disposer)
return observer
}
#endif
Expand Down
Loading

0 comments on commit 678d653

Please sign in to comment.