ReactiveSwift是出自ReactiveCocoa小组的纯Swift风格FRP。ReactiveSwift提供了可组合、可声明以及灵活的原语,建立在时间流的大概念之下。
这些原语可用于统一展现通用Cocoa以及泛型编程模式,这些都是观察者的行为基础。例如委派模式、回调闭包、通知、控制动作、响应者链事件、Future/Promise以及K/V的监控。所有的这些不同的机制都使用相同的方法进行呈现,可以很方便的将这些组合在一起,更少的意大利面条式的代码以及状态来弥补其中的缝隙。
示例代码:
// Purchase from the vedig machie with a specific optio.vedigMachie.purchase .apply(sackId) .startWithResult { result switch result { case let .success(sack): prit("Sack: \(sack)") case let .failure(error): // Out of stock? Isufficiet fud? prit("Trasactio aborted: \(error)") } }// The vedig machie.class VedigMachie { let purchase: Actio<It, Sack, VedigMachieError> let cois: MutableProperty<It> // The vedig machie is coected with a sales recorder. iit(_ salesRecorder: SalesRecorder) { cois = MutableProperty(0) purchase = Actio(state: cois, eabledIf: { $0 > 0 }) { cois, sackId i retur SigalProducer { observer, _ i // The sales magic happes here. // Fetch a sack based o its id } } // The sales recorders are otified for ay successful sales. purchase.values.observeValues(salesRecorder.record) }}编者注:
函数响应式编程(FuctioalReactiveProgrammig:FRP)是一种和事件流有关的编程方式,其角度类似EvetSoucig,关注导致状态值改变的行为事件,一系列事件组成了事件流。FRP是更加有效率地处理事件流,而无需显式去管理状态。
具体来说,FRP包括两个核心观点:
事件流,离散事件序列
属性properties,代表模型连续的值。
一系列事件是导致属性值发生变化的原因。FRP非常类似于GOF的观察者模式。
评论