Reactive Programming: Principles and a Simple KVO Implementation
Introduction In reactive programming, you don't need to think about the order of operations — you only need to care about the result. It's like the butterfly effect: one event ripples outward, affecting many things. These events propagate like streams and ultimately influence the outcome. To borrow an object-oriented phrase: everything is a stream. Reactive programming is not actually that complicated. KVO, which you probably use often, is a classic example of it. How KVO Works Internally KVO stands for . It uses a key to locate a property and observe changes to its value. The underlying mechanism is: when a property of a class is observed, the system uses the runtime to dynamically create a subclass of that class. It overrides the setter of the observed property in this derived class, and changes the object's pointer to point to the derived class. As a result, whenever the observed property is set, the derived class's setter is called. The overridden setter notifies the observer before and after calling the original setter. Using KVO is straightforward: 1. Add an observer: . 2. Implement the observation callback in the observer: . 3. Remove the observer: . The steps the system performs internally are: 1. Dynamically create (a subclass of ); 2. Modify the current object's pointer to point to ; 3. Whenever the object's setter is called, 's setter is invoked instead; 4. The overridden setter in first calls and then notifies the observer that the property has changed. A Simple KVO Implementation Add a category : Create a subclass of named and override its setter: In , switch to using the new category method to add the observer: Code All code from this article can be found on my GitHub .