Last active
March 22, 2017 03:08
-
-
Save iThinker/d4a8f1aa0b23029cc6cc006a161c95c1 to your computer and use it in GitHub Desktop.
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 | |
class CancellableDecorator { | |
private class Token { | |
var isValid = true | |
} | |
private var token: Token? | |
var delay = 0.75 | |
func scheduleCurried<Result>(_ executable: @escaping Completion<Result>) -> Completion<Result> { | |
return { completion in | |
self.cancel() | |
let operationToken = Token() | |
self.token = operationToken | |
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + self.delay) { | |
if operationToken.isValid { | |
executable { | |
result in | |
if operationToken.isValid { | |
completion(result) | |
} | |
} | |
} | |
} | |
} | |
} | |
func cancel() { | |
self.token?.isValid = false | |
} | |
deinit { | |
self.cancel() | |
} | |
} | |
typealias Completion<T> = (@escaping (T) -> Void) -> Void | |
class Executor { | |
func runTwoCurry(in1: String, in2: Int) -> Completion<Double> { | |
return { completion in | |
completion(Double(in1)! + Double(in2)) | |
} | |
} | |
} | |
let decorator = CancellableDecorator() | |
let executor = Executor() | |
executor.runTwoCurry(in1: "2", in2: 1)({ result in | |
String(result) | |
print("\(result)") | |
}) | |
executor.runTwoCurry(in1: "2", in2: 1)() { result in | |
String(result) | |
print("\(result)") | |
} | |
let curried = executor.runTwoCurry(in1: "2", in2: 1) | |
curried { result in | |
String(result) | |
print("\(result)") | |
} | |
decorator.scheduleCurried(curried)({ result in | |
String(result) | |
print("\(result)") | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment