Flux is the application architecture that Facebook uses for building client-side web applications.
- Unidirectional flow
- View - Store - Action - Dispatcher
Minimal library for swift that according to flux concept.
Swiflux is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod "Swiflux"
Requirements
- RxSwift 3.x (or higher)
- Swift 3.x (or higher)
import Swiflux
i. extends StoreBase
class UserStore: StoreBase
ii. Override some (optional)
override func buildDefaultState() {
}
override func bindEvents() {
}
iii. Subscribe Action and change state
- state : a data that store has. changing of state will be broadcast to views who subscribe.
class UserStore: StoreBase {
override func buildDefaultState() {
//default state value
setState(for: "greeting", state: "")
}
override func bindEvents() {
//subscribe action event "app:greeting"
Dispatcher.shared().on("app:greeting") { props in
guard let props = props else { return }
let firstName = props["firstName"] as! String
let lastName = props["lastName"] as! String
self.buildGreetMessage(first: firstName, last: lastName)
}
}
//BUISINESS LOGIC
func buildGreetMessage(first: String, last: String) {
var greet = "Hi~ there!"
if first.isEmpty && !last.isEmpty {
greet = "Hello, \(last)."
} else if !first.isEmpty && last.isEmpty {
greet = "Hi, \(first)."
} else if !first.isEmpty && !last.isEmpty {
greet = "Hello, \(first) \(last)!"
}
//change state, and notify to View
self.setState(for: "greeting", state: greet)
}
}
let userStore = UserStore()
//bind state data via UserStore
userStore.on("greeting") { greet in
let greet = greet as! String
self.greetingLabel.text = greet
}
//Send Action Event
Dispatcher.shared().send("app:greeting", props: [
"firstName": firstName as AnyObject,
"lastName": lastName as AnyObject
])
Refer Example source code
Ryan Song<iamchiwon@gmail.com>
Swiflux is available under the MIT license. See the LICENSE file for more info.