Created
April 19, 2018 05:48
-
-
Save yoching/36a451467a8a8bd65448f1f5dd9576f6 to your computer and use it in GitHub Desktop.
Simple Task implementation in swift
This file contains hidden or 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
typealias Completion<Value, Error: Swift.Error> = (Result<Value, Error>) -> Void | |
typealias TaskHandler<Value, Error: Swift.Error> = (@escaping Completion<Value, Error>) -> Void | |
struct Task<Value, Error: Swift.Error> { | |
private let handler: TaskHandler<Value, Error> | |
init(_ handler: @escaping TaskHandler<Value, Error>) { | |
self.handler = handler | |
} | |
func start(_ completion: @escaping Completion<Value, Error>) { | |
handler(completion) | |
} | |
func then<NewValue>(_ transform: @escaping (Value) -> Task<NewValue, Error>) -> Task<NewValue, Error> { | |
return .init { completion in | |
self.start { result in | |
switch result { | |
case .failure(let error): | |
completion(.failure(error)) | |
case .success(let value): | |
transform(value).start(completion) | |
} | |
} | |
} | |
} | |
} | |
enum Result<Value, Error: Swift.Error> { | |
case success(Value) | |
case failure(Error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment