[英]How organize action-state flow of upload/download methods using ReSwift
I'm building application using Redux architecture with ReSwift framework, most of applications processes described by action - reducer - state flow.我正在使用 Redux 架构和 ReSwift 框架构建应用程序,大多数应用程序流程由操作 - 减速器 - 状态流描述。 Now I have added two methods upload(image: UIImage, fileName: String) and download(fileName: String), which uploading and downloading images to Firebase storage.
现在我添加了两个方法 upload(image: UIImage, fileName: String) 和 download(fileName: String),它们将图像上传和下载到 Firebase 存储。 So, how I can describe theses methods using Redux flow?
那么,我如何使用 Redux 流程来描述这些方法呢? Well, I know how I can run downloading/uploading processes using middleware, but how I can get results of download/upload in store subscribers?
好吧,我知道如何使用中间件运行下载/上传过程,但是如何在商店订阅者中获得下载/上传的结果?
You can create actions that will either hold the results or an error like this:您可以创建将保存结果或错误的操作,如下所示:
struct ImageDownloadStartAction: Action {
let filename: String
}
struct ImageDownloadSuccessAction: Action {
let data: Data
}
struct ImageDownloadFailureAction: Action {
let error: Error
}
struct ImageUploadStartAction: Action {
let image: UIImage
let filename: String
}
struct ImageUploadSuccessAction: Action { }
struct ImageUploadFailureAction: Action {
let error: Error
}
Then in your completionHandler
or done
block, you can use the dispatch
function passed to the middleware to dispatch the success/failure action on the main thread (for example, DispatchQueue.main.async
) and use the value or error in your reducer.然后在您的
completionHandler
或done
块中,您可以使用传递给中间件的dispatch
函数在主线程(例如, DispatchQueue.main.async
)上调度成功/失败操作,并在您的减速器中使用值或错误。
For example (using PromiseKit
):例如(使用
PromiseKit
):
let networkMiddleware: Middleware<AppState> = { dispatch, getState in
return { next in
return { action in
next(action)
switch action {
case let action as ImageDownloadStartAction:
networkService.download(filename: action.filename)
.done { // automatically called on main thread in PromiseKit
dispatch(ImageDownloadSuccessAction(data: $0)
}
.catch { // automatically called on main thread in PromiseKit
dispatch(ImageDownloadFailureAction(error: $0)
}
default:
break
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.