Created
August 16, 2017 09:50
-
-
Save nsomar/b47642d52b95b39fd9daddcd36aaf333 to your computer and use it in GitHub Desktop.
AsyncAction implementation for Suas that performs a URL request
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
/// Callback called when URLSession operation completes | |
public typealias URLSessionActionCompletionBlock = (Data?, URLResponse?, Error?, DispatchFunction) -> Void | |
/// URL Session `AsyncAction` implementation to fetch data from the network asynchronously. Requires `AsyncMiddleware` to be added to the store. | |
/// | |
/// # Example | |
/// | |
/// ``` | |
/// let action = URLSessionAsyncAction(url: ...) { data, response, error, dispatch in | |
/// // Parse data and prepare models | |
/// dispatch(DataFetchedAction(parsed)) | |
/// } | |
/// ``` | |
public struct URLSessionAsyncAction: AsyncAction { | |
private let urlSession: URLSession | |
private let urlRequest: URLRequest | |
private let completionBlock: URLSessionActionCompletionBlock | |
/// Create a URLSession AsyncAction | |
/// | |
/// - Parameters: | |
/// - url: the url to fetch | |
/// - urlSession: (optional) the url session to use. When not set a default one will be used. | |
/// - completionBlock: callback to call when the url operation is ended. In this block `dispatch` is used to dispatch new actions | |
/// - Returns: an async action to dispatch | |
public init(url: URL, | |
urlSession: URLSession = URLSession(configuration: .default), | |
completionBlock: @escaping URLSessionActionCompletionBlock) { | |
self.init(urlRequest: URLRequest(url: url), urlSession: urlSession, completionBlock: completionBlock) | |
} | |
/// Create a URLSession AsyncAction | |
/// | |
/// - Parameters: | |
/// - urlRequest: the url request to fetch | |
/// - urlSession: (optional) the url session to use. When not set a default one will be used. | |
/// - completionBlock: callback to call when the url operation is ended. In this block `dispatch` is used to dispatch new actions | |
/// - Returns: an async action to dispatch | |
public init(urlRequest: URLRequest, | |
urlSession: URLSession = URLSession(configuration: .default), | |
completionBlock: @escaping URLSessionActionCompletionBlock) { | |
self.urlRequest = urlRequest | |
self.urlSession = urlSession | |
self.completionBlock = completionBlock | |
} | |
public func execute(getState: @escaping GetStateFunction, dispatch: @escaping DispatchFunction) { | |
// Perform a data task with the reuest | |
urlSession.dataTask(with: urlRequest) { data, response, error in | |
// When its done, call the completion block | |
self.completionBlock(data, response, error, dispatch) | |
}.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment