Created
April 12, 2017 15:56
-
-
Save eugeniobaglieri/1444992cc4220496bf02a2b4ef08708e 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
// | |
// NetworkOperation.swift | |
// OperationsTest | |
// | |
// Created by Eugenio Baglieri on 11/04/17. | |
// Copyright © 2017 Eugenio Baglieri. All rights reserved. | |
// | |
import Foundation | |
public enum NetworkError: Error { | |
case badInput | |
case noData | |
case unacceptableResponse(Int) | |
} | |
// | |
// Operation.swift | |
// NetworkLayer | |
// | |
// Created by Eugenio Baglieri on 08/04/17. | |
// Copyright © 2017 Eugenio Baglieri. All rights reserved. | |
// | |
import Foundation | |
protocol NetworkOperation { | |
associatedtype Output | |
typealias Result = () throws -> Output | |
typealias CompletionHandler = (_ result: Result) -> Void | |
/// Request to execute | |
var request: Request { get } | |
/// Initialize the operation | |
/// | |
/// - Parameter dispatcher: dispatcher | |
/// - Parameter completionHandler: the completion handler to call when the operation is complete. | |
init(environment: Environment, completionHandler: CompletionHandler?) | |
} | |
public class NetworkOperation<Output>: Operation { | |
public typealias Result = () -> Output | |
public typealias CompletionHandler = (_ result: Result) -> Void | |
let internalQueue: OperationQueue | |
let requestOperation: RequestOperation | |
let completion: CompletionHandler? | |
init(environment: Environment, request: Request, completionHandler: CompletionHandler?) throws { | |
requestOperation = RequestOperation(environment: environment, request: request) | |
completion = CompletionHandler | |
internalQueue = OperationQueue() | |
internalQueue.delegate | |
internalQueue.isSuspended = true | |
super.init() | |
} | |
public override func execute() { | |
guard isCancelled == false else { finish() } | |
let decodeOperation = BlockOperation { | |
let result = decodeResponse(requestOperation.response!) | |
} | |
let finishOperation = BlockOperation { | |
DispatchQueue.main.async { | |
completion? { result } | |
} | |
} | |
} | |
public func decodeResponse(_ response: Response) -> Result { | |
fatalError("decodeResponse not overridden") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment