iamchiwon / Swiflux

Minimal flux library for swift

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Swiflux

CI Status Version License Platform

Intro

What is Flux?

Flux is the application architecture that Facebook uses for building client-side web applications.

Core of Flux

  • Unidirectional flow
  • View - Store - Action - Dispatcher

Swiflux

Minimal library for swift that according to flux concept.

Installation

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)

Example

1. Import library

import Swiflux

2. Write Store class

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

3. Bind Store with View

let userStore = UserStore()

//bind state data via UserStore
userStore.on("greeting") { greet in
    let greet = greet as! String
    self.greetingLabel.text = greet
}

4. Send Action events to Dispatcher

//Send Action Event
Dispatcher.shared().send("app:greeting", props: [
    "firstName": firstName as AnyObject,
    "lastName": lastName as AnyObject
])

Refer Example source code

Author

Ryan Song<iamchiwon@gmail.com>

License

Swiflux is available under the MIT license. See the LICENSE file for more info.

About

Minimal flux library for swift

License:MIT License


Languages

Language:Swift 96.5%Language:Shell 2.9%Language:Objective-C 0.3%Language:Ruby 0.3%