Created
October 14, 2017 20:47
-
-
Save jakebromberg/c47235c2c529bbd64b70119930f31527 to your computer and use it in GitHub Desktop.
Encapsulates the steps necessary to tear down some unit of work, typically an asynchronous operation like a network task.
This file contains 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 | |
/// `Disposable` encapsulates the steps necessary to tear down some unit of work, typically an asynchronous operation | |
/// like a network task. | |
public protocol Disposable { | |
/// Disposes the object. This may be invoked multiple times, but only performs its side-effects once. | |
func dispose() | |
} | |
extension URLSessionTask: Disposable { | |
func dispose() { | |
cancel() | |
} | |
} | |
extension Operation: Disposable { | |
func dispose() { | |
cancel() | |
} | |
} | |
/// `AnyDisposable` takes a block and invokes it once on dispose. This class guarantees thread safety. | |
public final class AnyDisposable: Disposable { | |
public typealias Action = () -> () | |
// the disposable is optional because we nil it out after it's invoked to prevent multiple invocations. | |
private var disposable: Action? | |
private let queue = DispatchQueue(label: "disposable") | |
public init(_ disposable: @escaping Action) { | |
self.disposable = disposable | |
} | |
public func dispose() { | |
self.queue.async { | |
if let disposable = self.disposable { | |
disposable() | |
} | |
self.disposable = nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment