FluxSwift 0.2.2

FluxSwift 0.2.2

Koji Murata 维护。



 
依赖
RxSwift~> 5.0.1
RxRelay~> 5.0.1
 

FluxSwift 0.2.2

  • 作者
  • malt03

FluxSwift Build Status SwiftPM compatible License

FluxSwift 是采用 RxSwift 实现的完全类型安全的 Flux 实现。
与 Redux 不同,Store 不是一个单例。

用法

Store

struct User: Store {
    let name: String
}

Action

在 FluxSwift 中,与普通的 Flux 不同,reduce 函数在 Action 中定义。
这提供了一种类型安全的实现,并防止了 Fat Store。

struct ChangeName: Action {
    let newName: String
    func reduce(store: User) -> User? { // If you don't dispatch the Action to the Store, you can return nil.
        var tmp = store
        tmp.name = newName
        return tmp
    }
}

注册、订阅和发送

let user: RegisteredStore<User> = User(name: "malt03").register() // register the store to Dispatcher
print(user.entity.name) // "malt03"
let disposable = user.subscribe(onNext: { (user) in print(user.name) }) // subscribe
ChangeName(newName: "malt04").dispatch() // dispatch

定义嵌套 Store

设置childStores的值,这是一个符合Store协议的实例变量。
如果按以下方式实现,当用户发生变化时,将在Session中检测到变化。

struct Session: Store {
    var token: String
    let user: RegisteredStore<User>

    var childStores: [AnyRegisteredStore] { [user.any()] }
}

使用 Codable 的 Store

当 Store 符合 Codable 协议时,RegisteredStore 也符合 Codable。

extension User: Codable {}
let json = try! JSONEncoder().encode(user) // { "name": "malt03" }
print(JSONDecoder().decode(RegisteredStore<User>.self, from: json).entity.name) // "malt03"

ThrowsAction

struct ChangeName: ThrowsAction {
    let newName: String
    func reduce(store: User) -> User? {
        var tmp = store
        store.name = newName
        return store
    }
}
try ChangeNameFromFile(nameFile: url).dispatch()

IdentifiableStore

通过遵守 IdentifiableStore 协议,您可以将操作仅发送到具有指定 ID 的 Store。

struct IdentifiableCounter: IdentifiableStore {
    let id: String
    var count = 0
    
    struct Increment: Action {
        func reduce(store: IdentifiableCounter) -> IdentifiableCounter? {
            var tmp = store
            tmp.count += 1
            return tmp
        }
    }
}

let a0 = IdentifiableCounter(id: "a").register()
let a1 = IdentifiableCounter(id: "a").register()
let b = IdentifiableCounter(id: "b").register()
IdentifiableCounter.Increment().dispatch(to: "a")
IdentifiableCounter.Increment().dispatch()
print(a0.entity.count) // 2
print(a1.entity.count) // 2
print(b.entity.count) // 1

具有可观察性的操作

struct Store: FluxSwift.Store {
    var x: Int = 0
    
    struct Set: Action {
        let x: Int
        func reduce(store: Store) -> Store? { Store(x: x) }
    }
}

let store = Store().register()
let relay = PublishRelay<Int>()
let disposable = relay.dispatchAction(action: { Store.Set(x: $0) })

relay.accept(1)

安装

SwiftPM(推荐)

  • 在Xcode中,点击文件 > Swift包 > 添加包依赖...
  • 输入https://github.com/malt03/FluxSwift.git