AsyncAction
public protocol AsyncAction: Action
Async action this type of action is intercepted by AsyncMiddleware
and is not dispatched to the reducer.
Recepie to use AsyncAction
- Create an
AsyncAction
action - In the block passed at init. Perform any operation (dispatching it on your queue)
- When result is ready, call
dispatch
passing a new action
If the AsyncMiddleware
receives an AsyncAction
it does the following:
- Call action.execute passing in the dispatch and get state functions
- Stops the action from propagating to other middlewares and reducers
Example
Performing an async loading from disk
struct MyDiskAsyncAction: AsyncAction {
func execute(getState: @escaping GetStateFunction, dispatch: @escaping DispatchFunction) {
// Perform some work in a background thread
DispatchQueue(label: "MyQueue").async {
// Load from disk
// Process loaded
// Do more work
// Maybe consult the current state
let currentState = api.state
// At a latter time dont forget to dispatch
dispatch(DataLoadedAction(data: data))
}
}
store.dispatch(action: MyDiskAsyncAction())
Performing an async network request
struct MyURLAsyncAction: AsyncAction {
func execute(getState: @escaping GetStateFunction, dispatch: @escaping DispatchFunction) {
// First dispatch some action syncrhonously
dispatch(SomeAction(...))
let session = URLSession(configuration: .default)
// perform a dataTask
session.dataTask(with: urlRequest) { data, response, error in
if let data = data {
// Do something with the data
dispatch(RequestSucceeded(data: data))
} else if let error = error {
// Error happenend
dispatch(RequestFaile(data: data))
}
}
}
store.dispatch(action: MyURLAsyncAction())
-
Execution block that is executed in the
AsyncMiddleware
If theAsyncMiddleware
receives anAsyncAction
it does the following:- Call action.execute passing in the dispatch and get state functions
- Stops the action from propagating to other middlewares and reducers
Declaration
Swift
func execute(getState: @escaping GetStateFunction, dispatch: @escaping DispatchFunction)