-
Notifications
You must be signed in to change notification settings - Fork 1
Middleware Thunk
Cheng Zhang edited this page Apr 9, 2020
·
2 revisions
After careful consideration, decided not to add Middleware
or Thunk
to the library.
Because it just adds unnecessary layer, as SwiftUI maintains State separately, no need to dispatch Command asynchronously and then reduce on the root State like redux.js.
For example, when fetch feeds it can simply make async call directly on FeedListState
, and then FeedListState
reacts to completion
which contains data or error.
Below is the experiment code I wrote for Thunk Middleware:
ThunkMiddleware.swift,
class ThunkMiddleware: Subscriber {
public override func reduce(action: ReduxActionProtocol) {
switch action {
case let command as FetchFeedsCommand:
Services.shared.fetchFeeds(endPoint: command.endPoint) { feeds in
dispatch(action: FetchFeedsResultAction(feeds: feeds, error: nil))
}
break
default:
break
}
}
}
dispatch(action: FetchFeedsCommand(endPoint: Self.feedEndpoint))
On FeedListState
,
public override func reduce(action: ReduxActionProtocol) {
switch action {
case let fetchFeedsResultAction as FetchFeedsResultAction:
guard let feeds = fetchFeedsResultAction.feeds else {
assertionFailure("Failed to fetch feeds. Error - \(fetchFeedsResultAction.error).")
return
}
self.feeds = feeds
break
default:
feeds = feeds.map { $0.reduce(action: action) }
}
}