0%

仿ReactiveCocoa实现响应式编程框架

响应式编程

In computing, reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change. With this paradigm it is possible to express static (e.g., arrays) or dynamic (e.g., event emitters) data streams with ease, and also communicate that an inferred dependency within the associated execution model exists, which facilitates the automatic propagation of the changed data flow.

实现响应式框架

信号

实现方式

对NSObject进行扩展,增加产生信号的实例方法。

每个信号对应一个需要被响应的事件。信号按照命名规范命名并绑定在实例上。

信号内记录所有订阅者,如此一来,事件触发时信号便会通知所有订阅者响应。

对selector的响应

实现方式

所有被订阅的method在被调用前,都需要发出信号去告知所有该事件的观察者。

既然所有被订阅的method调用前都需要执行信号发送流程,那么可以把这个信号发送流程写入forwardInvocation内。

之后通过重设被订阅的method的imp指针为_objc_msgForward,将被订阅的method直接导向消息转发流程。

同时将被订阅的method原有的imp指针交给动态创建的别名方法,在forwardInvocation完成信号发送后,再调用别名方法。