- Flux is the application architecture that Facebook uses for building client-side web applications.
- FlSwift is Flux like architecture library written in Swift.
- Using one-way data flow makes it easier to understand state management.
- Action to handle value increase / decrease
enum NumberAction: Action {
case increase(Int)
case decrease(Int)
}
- Dipatcher to handle actions.
- This sample defines dispatcher as ActionCreator
class NumberActionCreator {
static let shared = NumberActionCreator()
private init() {}
let dispatcher = FlSwift.Dispatcher<NumberAction>.shared
}
- You can define the state of the app that handles increasing and decreasing values as follows.
class NumberState: State {
typealias ActionType = NumberAction
func reduce(action: NumberAction) {
switch action {
case .increase(let value):
number.accept(number.value + value)
case .decrease(let value):
number.accept(number.value - value)
}
}
var number = BehaviorRelay<Int>(value: 0)
}
- Reflect the change in the value in the view.
- This sample uses Rxswift to bind to the view
final class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
store.state.number
.asObservable()
.map({ String($0) })
.bind(to: numberLabel.rx.text)
.disposed(by: disposeBag)
}
@IBAction private func plusButtonTapped(_ sender: Any) {
NumberActionCreator.shared.dispatcher.dispatch(.increase(1))
}
@IBAction private func minusButtonTapped(_ sender: Any) {
NumberActionCreator.shared.dispatcher.dispatch(.decrease(1))
}
private let disposeBag = DisposeBag()
@IBOutlet private weak var numberLabel: UILabel!
private lazy var store: Store<NumberState> = {
let state = NumberState()
let store = Store(state: state)
store.subscribe()
return store
}()
}
- Xcode 10.3
- Swift 5.0
Add the pod FlSwift
# Podfile
use_frameworks!
target 'YOUR_TARGET_NAME' do
pod 'FlSwift'
end
$ pod install
Add this to Cartfile
git "[email protected]:CChannel/FlSwift.git"
$ carthage update
Add this to Package.swift
dependencies: [
.package(url: "https://github.com/CChannel/FlSwift.git", from: "0.0.1")
]
$ swift build
There's still a lot of work to do here. We would love to see you involved. You can find all the details on how to get started in the Contributing Guide.
FlSwift is released under the MIT license. See LICENSE for details.