Skip to content

Instantly share code, notes, and snippets.

Created August 16, 2017 09:52
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
AsyncAction implementation for Suas that read from disk in the background
/// 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 {
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