Technology

The Dispatcher as a Stream, Part 1: FRP && ReactJS


If you look at the existing Flux architecture, at the 10,000ft level, it already uses functional reactive programming.

  • The Dispatcher is an Observable accepting inputs (Actions)
  • The Dispatcher re-emits Actions to its Observers.
  • Stores observe the Dispatcher and act accordingly.

We can thus replace the Dispatcher with an Observable that accepts inputs. In BaconJS, for example, it’s called a Bus. The Dispatcher is just this in FRP:

//AppDispatcher.js
import Bacon from 'baconjs'

export default new Bacon.Bus()

Actions can look like this:

//TodoActions.js
import AppDispatcher from 'AppDispatcher'

export default {

  addTodo: function(todo) {

    AppDispatcher.push({
       channel: 'todo',
       actionType: 'create',
       data: todo
   })
 }    
}

So far, the FRP ReactJS app looks like a run-of-the-mill Flux app. Things get interesting when we get to Stores…

By the way, we use a single global dispatcher to reap the benefits of FRP—the Actions passed to the Dispatcher plus the states of the stores completely define the App state at any moment in time. We can therefore easily replay the state of the App (for debugging). Did I also mention we get undo functionality for free? Pretty. Freakin’. Cool.

Advertisements

2 thoughts on “The Dispatcher as a Stream, Part 1: FRP && ReactJS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s