Skip to content

Instantly share code, notes, and snippets.

@nsomar
Created August 16, 2017 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nsomar/95bdb3f57cb482dd3ae21255770671f1 to your computer and use it in GitHub Desktop.
Save nsomar/95bdb3f57cb482dd3ae21255770671f1 to your computer and use it in GitHub Desktop.
AsyncAction implementation for Suas that write to disk in the background
/// Callback called when Disk IO write operation completes
public typealias DiskWriteActionCompletionBlock = (Bool, DispatchFunction) -> Void
/// Disk Write `AsyncAction` implementation to write data to the disk asynchronously. Requires `AsyncMiddleware` to be added to the store.
///
/// # Example
///
/// ```
/// let action = DiskWriteAsyncAction(path: ..., data: ...) { succeeded, dispatch in
/// // After data is written, dispatch an action
/// dispatch(DataWrittenToDisk(succeeded))
/// }
/// ```
public struct DiskWriteAsyncAction: AsyncAction {
static let defaultDispatchQueue = DispatchQueue(label: "DISK_WRITE_ASYNC_ACTION")
private let path: String
private let data: Data
private let fileManager: FileManager
private let dispatchQueue: DispatchQueue
private let completionBlock: DiskWriteActionCompletionBlock
/// Create a Write DiskIO AsyncAction
///
/// - Parameters:
/// - path: path to write to disk
/// - data: data to write to 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,
data: Data,
fileManager: FileManager = .default,
dispatchQueue: DispatchQueue = defaultDispatchQueue,
completionBlock: @escaping DiskWriteActionCompletionBlock) {
self.path = path
self.data = data
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 {
// When data is written call the block
let result = self.fileManager.createFile(atPath: self.path, contents: self.data, attributes: nil)
self.completionBlock(result, dispatch)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment