mirror of
https://github.com/ivanvorobei/SwiftUI.git
synced 2026-04-10 11:14:08 +02:00
Add Flux
This commit is contained in:
34
Examples/Flux/SwiftUI-Flux/Store.swift
Executable file
34
Examples/Flux/SwiftUI-Flux/Store.swift
Executable file
@@ -0,0 +1,34 @@
|
||||
import SwiftUI
|
||||
import Combine
|
||||
|
||||
final class Store<State, Action>: BindableObject {
|
||||
typealias Reducer = (State, Action) -> State
|
||||
|
||||
let didChange = PassthroughSubject<State, Never>()
|
||||
|
||||
var state: State {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return _state
|
||||
}
|
||||
|
||||
private let lock = NSLock()
|
||||
private let reducer: Reducer
|
||||
private var _state: State
|
||||
|
||||
init(initial state: State, reducer: @escaping Reducer) {
|
||||
_state = state
|
||||
self.reducer = reducer
|
||||
}
|
||||
|
||||
func dispatch(action: Action) {
|
||||
lock.lock()
|
||||
|
||||
let newState = reducer(_state, action)
|
||||
_state = newState
|
||||
|
||||
lock.unlock()
|
||||
|
||||
didChange.send(newState)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user