Fluxful 1.2.1

Fluxful 1.2.1

Natan Zalkin 维护。



Fluxful 1.2.1

  • 作者:Natan Zalkin
  • Natan Zalkin

Fluxful

License Language Build Status Coverage Status

关于

Fluxful 是一个简约主义框架,提供了遵循 Flux 设计模式的协议和扩展,用于管理全局应用状态。Fluxful 用 Swift 5 编写,旨在生成独立的模块,封装应用业务逻辑的不同部分。Fluxful 模块提供工具,使您可以轻松跟踪存储变更并渲染始终同步当前状态的 UI。

有关 Flux 模式的更多信息,请参阅此处

Fluxful 的流程图类似于 Redux。您可以在这里了解更多信息。

Redux

安装

Swift 包管理器

在 XCode 中添加 “Fluxful” 依赖

CocoaPods

pod 'Fluxful'

添加支持存储更改通知和观察的功能

pod 'Fluxful/Reactive'

这将安装Fluxful扩展,该扩展允许在不使用Combine或其他库的情况下观察存储更改。使用此扩展,您可以通过调用“ addObserver”方法并提供更改处理闭包来订阅存储更改。 "addObserver”返回一个订阅对象。存储订阅在取消或处置订阅对象之前将保持活跃。您可以在存储动作处理程序中使用“ notify”方法,并传递包含已更改存储属性信息的一个“PartialKeyPath”对象数组的印象,向订阅者发送通知。

使用说明

首先,您需要声明动作

struct SetAmountAction {
    let value: UInt
}
    
struct FetchAmountAction {}

当您需要实现处理特定动作的中间件,通过运行异步工作并更新存储来实现时

class MyMiddleware: Middleware {
    
    var handlers: [ObjectIdentifier: Any] = [:]
    
    init(dispatcher: Dispatcher) {
        register(FetchAmountAction.self) { [weak dispatcher] (subject, action) in
            
            /* Here you can run code in background or make API call */ 
            
            // After that you should back to main thread and update the store
            DispatchQueue.main.async { [weak store] in
                dispatcher?.dispatch(SetAmountAction(value: /* Value received */))
            }
            
            // You can just intercept the action if it will not being handled in the store anyway
            return .stop()
        }
    }
}

此时,存储只是一个状态容器

class MyStore: Store {

    private(set) var amount = 0
    
    var reducers: [ObjectIdentifier: Any] = [:]
    var middlewares: [Middleware] = []
    
    init() {
        // Connect middleware
        middlewares.append(MyMiddleware(dispatcher: self))
        
        register(SetAmountAction.self) { (subject, action) in
            // Mutate state
            subject.amount = action.value
            // Notify observers. When using with SwiftUI, this part would not needed. Don't forget to mark mutable properties with @Published
            subject.notify(keyPathsChanged: [\MyStore.amount])
        }
    }
}

就是这样!现在每当向存储发送动作时,存储状态发生变化,都会发送通知。通过使用‘addObserver’方法添加观察者,您可以跟踪状态变化并相应地更新UI。

作者

内坦·扎尔金 [email protected]

许可证

Fluxful遵循MIT许可证。有关更多信息,请参阅LICENSE文件。