Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AsyncAction implementation for Suas that performs a URL request
/// 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