Skip to content

Instantly share code, notes, and snippets.

@ericlewis
Last active January 14, 2025 20:11
Show Gist options
  • Select an option

  • Save ericlewis/64953d31d36cdf172b59fe602147fc26 to your computer and use it in GitHub Desktop.

Select an option

Save ericlewis/64953d31d36cdf172b59fe602147fc26 to your computer and use it in GitHub Desktop.
Example of using ReSwift with SwiftUI
import SwiftUI
import ReSwift
// MARK: ReSwift Example Setup
struct AppState: StateType {
var counter: Int = 0
}
struct CounterActionIncrease: Action {}
struct CounterActionDecrease: Action {}
func counterReducer(action: Action, state: AppState?) -> AppState {
var state = state ?? AppState()
switch action {
case _ as CounterActionIncrease:
state.counter += 1
case _ as CounterActionDecrease:
state.counter -= 1
default:
break
}
return state
}
let mainStore = Store<AppState>(
reducer: counterReducer,
state: nil
)
// MARK: ContentView
struct ContentView: View {
// MARK: Private Properties
@ObservedObject private var state = ObservableState(store: mainStore)
// MARK: Body
var body: some View {
VStack {
Text(String(state.current.counter))
Button(action: state.dispatch(CounterActionIncrease())) {
Text("Increase")
}
Button(action: state.dispatch(CounterActionDecrease())) {
Text("Decrease")
}
}
}
}
// MARK: ObservableState
public class ObservableState<S>: ObservableObject where S: StateType {
// MARK: Public properties
@Published public var current: S
// MARK: Private properties
private var store: Store<S>
// MARK: Lifecycle
public init(store: Store<S>) {
self.store = store
self.current = store.state
store.subscribe(self)
}
deinit {
store.unsubscribe(self)
}
// MARK: Public methods
public func dispatch(_ action: Action) {
store.dispatch(action)
}
public func dispatch(_ action: Action) -> () -> Void {
{
self.store.dispatch(action)
}
}
}
extension ObservableState: StoreSubscriber {
// MARK: - <StoreSubscriber>
public func newState(state: S) {
DispatchQueue.main.async {
self.current = state
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment