Created
August 16, 2017 09:52
-
-
Save nsomar/67726fe36e377eb582c9486d732ad57d to your computer and use it in GitHub Desktop.
AsyncAction implementation for Suas that read from disk in the background
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 Disk IO read operation completes | |
public typealias DiskReadActionCompletionBlock = (Data?, DispatchFunction) -> Void | |
/// Disk Read `AsyncAction` implementation to read data from the disk asynchronously. Requires `AsyncMiddleware` to be added to the store. | |
/// | |
/// # Example | |
/// | |
/// ``` | |
/// let action = DiskReadAsyncAction(path: ...) { data, dispatch in | |
/// // Dispatch a new action | |
/// dispatch(DataFetchedAction(data)) | |
/// } | |
/// ``` | |
public struct DiskReadAsyncAction: AsyncAction { | |
static let defaultDispatchQueue = DispatchQueue(label: "DISK_READ_ASYNC_ACTION") | |
private let path: String | |
private let fileManager: FileManager | |
private let dispatchQueue: DispatchQueue | |
private let completionBlock: DiskReadActionCompletionBlock | |
/// Create a Read DiskIO AsyncAction | |
/// | |
/// - Parameters: | |
/// - path: path to read from disk | |
/// - fileManager: (optional) the file manager to use. When not passed it defaults to `FileManager.default` | |
/// - dispatchQueue: (optional) the dispatch queue to use when accessing disk. When not passed it defaults to `DispatchQueue(label: "IOMIDDLEWARE_IO_QUEUE") | |
/// - completionBlock: callback to call when data is read from disk. In this block `dispatch` is used to dispatch new actions | |
/// - Returns: an async action to dispatch | |
public init(path: String, | |
fileManager: FileManager = .default, | |
dispatchQueue: DispatchQueue = defaultDispatchQueue, | |
completionBlock: @escaping DiskReadActionCompletionBlock) { | |
self.path = path | |
self.fileManager = fileManager | |
self.dispatchQueue = dispatchQueue | |
self.completionBlock = completionBlock | |
} | |
public func execute(getState: @escaping GetStateFunction, dispatch: @escaping DispatchFunction) { | |
// Perform action on a background thread | |
dispatchQueue.async { | |
if | |
let data = self.fileManager.contents(atPath: self.path) { | |
// When data is loaded call the block | |
self.completionBlock(data, dispatch) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment