AtlasSwift 0.1.0

AtlasSwift 0.1.0

Giuseppe Salvo 维护。



Atlas Swift Store

Atlas 是一个没有 reducer 层的用于swift应用的redux store

Version License Platform

安装

Atlas 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中:

pod 'AtlasSwift'

如何工作

有 3 个主要组件

  • 状态
  • 行为
  • 守卫

状态

// The state should be always a struct, to ensure immutability
struct CountState {
    var count: Int
}

let store = Atlas(state: CountState(
    count: 0
))

行为

行为可以是同步或异步的

struct Increment: AtlasAction {
    func handle(state: CountState, context: AtlasActionContext<CountState>) {
        var newState   = state
        newState.count = result
        context.complete(newState)
        // context.error(YourError)
    }
}

store.dispatch(Increment())

// With a completition callback
store.dispatch(Increment()) { (error?, state) in
    print("done! ", state.count)
}

守卫

守卫追踪store的生命周期。未来,它们还将包括类似中间件的功能。

struct Logger: AtlasGuard {
    // By default, this function returns true
    func shouldUpdate<A: AtlasAction>(state: State, action: A) -> Bool {
        return true
    }

    func willUpdate<A: AtlasAction>(state: State, action: A) {
        print("will update!", state.count)
    }
    
    func didUpdate<A: AtlasAction>(state: State, action: A) {
        print("update!", state.count)
    }
}

let store = Atlas(state: YourState(), guards: [ Logger() ])

订阅

extension YourController: AtlasSubscriber {

    override func viewDidAppear() {
        super.viewDidAppear()
        store.subscribe(self)
    }
    
    func newState(_ state: CountState) {
        print("count state changed!")
    }
}

订阅者应该更新

避免不必要的更新并订阅store的特定部分。默认情况下,shouldUpdate函数始终返回true。要使用此方法,状态应该是值类型。

extension YourController: AtlasSubscriber {

    // subscription code...

    func shouldUpdate(prevState: CountState?, newState: CountState) -> Bool {
        return prevState?.count != newState.count
    }
}

注意

  • Atlas使用序列队列来分发每个动作,因此您可以确信您的动作将以调用顺序执行
  • dispatch函数是异步的,以避免死锁。要跟踪其结束,可以使用completion参数
  • subscribe函数还有一个名为"queue"的第二个参数,用于在特定队列上订阅一个类。

这就是全部!

灵感来自ReSwift和Redux

许可证

Atlas可在MIT许可证下获得。有关更多信息,请参阅LICENSE文件。