Reactive Programming

I don’t know if I would go so far as to call Reactive Programming a design pattern, but there are people who do. Most of us have experienced it but we didn’t know it had a name. The most common application for reactive programming is in spread sheets. If you place a formula in the cell of a spread sheet and you change cells that the formula depends on, the data in the formula cell magically changes.

You say yup, that’s how it works but has does that help me write code?

The most effective place that I have found for reactive programming is mobile device user interfaces. That said, any user interface that can be modified by outside forces is an ideal candidate. If we consider face-book, twitter, or any other social media site, people are always changing their avatar or making new posts and we would like our screens to update in real time.

If we have a local list that contains all of the most recent updates then we could poll that list or we could use a publish and subscribe mechanism to react to changes. If we push the publish and subscribe model to a base class that we call MonitoredObject and we identify a method on that base class called updateView() then we have a good foundation for a reactive framework.

Every object that implements MonitoredObject will have a List, String, Array, etc that the base class will monitor. If the base class detects a change, it will automatically call the updateView() method with the updated data. If you have a phone list and it gets updated by another user, your phone list’s updateView() method will refresh your phone list in real time. Your phone list application didn’t have to do anything to poll or subscribe, it’s update method was called because the list changed.

You’re probably saying that this is no different than publish/subscribe or observable/observer patterns and you are almost right. The difference is that the observer/observable mechanism is designed once in the base class rather than in all the classes that you want to be dynamically monitored. The base class can be applied to things like arrays and strings where the program automatically computes the result of a change in their values.

If the program is the dog and the data the tail, reactive programming is the tail wagging the dog. For applications that follow the Model-View-Controller paradigm, the changes in the data model are automatically displayed in the view.

It took me a while to understand the value of this approach, but having worked with it for a while now, I am starting to see how designing this way can save a substantial amount of work. I make data objects monitored and as they change the program automatically adjusts to present a different outcome.

This entry was posted in General and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *