As you may see, I added two new methods: subscribe and subscribeOpt. Both do the same thing: adding a subscription. But one returns Cancelable and another – Option[Cancelable]. With these new methods our tiny Dispatcher class looks like a library a bit more…

We have a case class State, that describes the state of our application. We have the initialState, which is an instance of State.

We create an instance of Dispatche[State]. We should pass this instance as a parameter to every React element, that is intended to emit events or to subscribe on events. In other words: every React element that participates in the dataflow must have a reference to the same instance of Dispatcher as a parameter.

When we want to change the state of the application we call the dispatch method with a parameter, which is a pure function of type State => State.

To watch for the application state changes, we can use a subscribe method (or a supscribeOpt method), which takes two parameters: a function of type State=>Unit, and a function of type State=>Boolean (optional).The first parameter is a procedure that takes a current application state and uses it to change the state of the React Element (subscriber).The second parameter (optional) is used to filter changes of the application state.

This example demonstrates not only usage of the Dispatcher class but also usage of Sortable.js with React.

We have a sortable list here. It’s the TodoList React Component. This is a stateless element, which is re-mounted every time the state of the application is changed. So we need to create a new instance of Sortable class after every such change. The ref attribute will help us. When the ref attribute is used on a custom component declared as a class, the ref callback receives the mounted instance of the component as its argument.

There are two methods that can change the state of the application: onChange and handleSubmit. The first one is applied every time the user has entered a letter. And the second one is called when user has pushed the button.

There is only one subscriber in this example: the application component itself. It’s a stateful component. When changes occur, its state is modified to be equal to application current state.