Files
SwiftUI/Examples/Flux/SwiftUI-Flux/Store.swift
Ivan Vorobei 6d351cf167 Add Flux
2019-06-06 22:31:08 +03:00

35 lines
705 B
Swift
Executable File

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)
}
}