ShareState.md
December 30, 2022 ยท View on GitHub
Share state
- Open
MainFeature.swift - Add new action to open next module
extension MainFeature {
enum Action: Equatable {
// ...
case random
}
}
- Add new middleware
static func middleware(environment: Environment) -> [Middleware<MainFeature.State, MainFeature.Action>] {
var timerCancellable: [AnyCancellable] = []
return [
// ...
// Add following to the end of array
createMiddleware(environment: environment, { dispatch, getState, action, environment in
guard action == .random else { return }
DispatchQueue.main.async { [weak environment] in
environment?.moduleOutput.mainModuleDidTapRandomButton()
}
})
}
}
- Update reducer
static func reducer() -> Reducer<MainFeature.State, MainFeature.Action> {
static func reducer() -> Reducer<MainFeature.State, MainFeature.Action> {
return .init { state, action in
switch action {
// ...
case .stopAutoIncrement:
var state = state
state.isAutoIncrementEnabled = false
return state
case .random:
return state
}
}
}
}
- Update first middleware
extension MainFeature {
static func middleware(environment: Environment) -> [Middleware<MainFeature.State, MainFeature.Action>] {
var timerCancellable: [AnyCancellable] = []
return [
createMiddleware({ dispatch, getState, action in
switch action {
// ...
case .startAutoIncrement, .stopAutoIncrement, .random:
break
}
}),
// ...
]
}
}
- Go to
MainViewController.swiftand add button to openRandomizermodule
final class MainViewController: UIViewController {
// ...
override func viewDidLoad() {
super.viewDidLoad()
// ...
self.autoIncrementButton = autoIncrementButton
let randomButton = UIButton(primaryAction: UIAction(handler: { [weak self] _ in
self?.store.dispatch(.random)
}))
randomButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(randomButton)
randomButton.topAnchor.constraint(equalTo: autoIncrementButton.bottomAnchor, constant: 20).isActive = true
randomButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
randomButton.setTitle("Open 'Random'", for: .normal)
randomButton.titleLabel?.font = .systemFont(ofSize: 20)
let label = UILabel()
// ...
}
}
- Run app and tap "Start" button
- Wait for a second
- Tap
Open 'Random'Button - Label will increase value every second
- Play with counter
- That's it!