Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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