FluxFramework
这是什么?
FluxFramework是一个用于Swift的轻量级Flux框架。
灵感来自
功能
- 最小化实现
- 单向数据流
- 不依赖其他库
安装
Carthage
在 Cartfile
文件中添加以下行
github "Scior/FluxFramework" ~> 0.1
CocoaPods
将以下行添加到 Podfile
target 'YOUR_TARGET_NAME' do
pod 'FluxFramework', '~> 0.1'
CocoaPods
使用方法
定义事件、动作和动作创建器
将事件(FluxEvent
)转换为动作(FluxAction
)的转换操作必须编写在 FluxActionConverter
中。操作可以是异步的。
事件和动作可以定义为 enum
。例如,
final class ActionConverter: FluxActionConverter {
enum Event: FluxEvent {
case add(Model)
case removeAll
}
enum Action: FluxAction {
case replaceModels([Model])
}
typealias Dependency = Void
static func convert(event: Event, dependency: Dependency, actionHandler: @escaping (Action) -> Void) {
switch event {
case .add(let model):
// let models = ...
actionHandler(.replaceModels(models))
case .removeAll:
// ...
actionHandler(.replaceParentComment([]]))
}
}
}
通常,下面的别名将是有用的。
typealias ActionCreator = FluxActionCreator<ActionConverter>
定义状态和存储
状态(FluxState
)存储了一些属性。每个属性的更改必须在 handle(action:)
中完成。
如果进行了任何修改,则 handle
的返回值应为 nil
,因为它通知所有订阅者返回值。
例如,
struct State: FluxState {
let identifier = UUID().uuidString
private(set) var models: [Model]
mutating func handle(action: ActionConverter.Action) -> State? {
switch action {
case .replaceModels(let models):
self.models = models
}
return self
}
}
还可以使用以下别名
typealias Store = FluxStore<State>
订阅和取消订阅
为了观察状态的修改,
let store = FluxStore<State>
let subscription = store.subscribe { state in
print(state.models.count)
}
可以进行明确的取消订阅,如下所示:
subsciption.unsubscribe()
触发事件
要触发事件,只需调用 fire
let actionCreator = FluxActionCreator<ActionConverter>
actionCreator.fire(.add(Model()))
actionCreator.fire([.add(Model()), .removeAll])
转换为RxSwift的Observable
FluxStore
可以按照以下方式转换为RxSwift的Observable
extension FluxStore: ObservableConvertibleType {
public func asObservable() -> Observable<State> {
return Observable.create { [weak self] observer -> Disposable in
guard let self = self else { return Disposables.create() }
let subscription = self.subscribe { state in
observer.on(.next(state))
}
return Disposables.create {
subscription.unsubscribe()
}
}
}
}
许可协议
FluxFramework 在 MIT 许可证下。
版权所有 (c) 2019 Suita Fujino