Skip to content

Tyrian Rx React: UI as Data Flow

A rebuild of the Elm Architecture with RxJS and React – actions as a stream, scan() folds the model, side effects stay at the edge – and what this proof of concept reveals about UI architecture that ages well.

≈ 12 min readSoftwareReactive

Tyrian Rx React: UI as Data Flow

When every component in a UI mutates its own state, the first thing the system loses is its timeline. A click here, a callback there, a setState somewhere in between – and three weeks later, nobody can say when the state flipped that triggered the bug. The debugger shows the result, but not the history. You see: count is 7, although it should be 3. You don’t see which sequence of events turned the 3 into a 7, in which order two responses from the server arrived, whether the user clicked faster than the network responded.

The Elm Architecture is built precisely against this loss of history. And because you only understand an architecture once you have rebuilt it yourself, that is what I did over the last few weeks: the Elm Architecture with RxJS and React – as a proof of concept, not as a framework. The repository is at github.com/MikeBild/reactish-elmish, and the README already warns in its second line: Don't use in production! That warning is meant seriously, and I will come back to it at the end. The value of the experiment lies elsewhere.

The Elm Architecture, reduced to the skeleton#

Elm – since version 0.17 from May of this year without signals, but with subscriptions instead – forces every application into the same shape:

  • a model that holds the entire state of the application as one value
  • an update function that computes a new model from the old model and a message
  • a view function that produces the rendering from the model
  • subscriptions for everything that comes in from outside: timers, WebSockets, browser events

None of this is optional, and none of it has a side exit. The compiler simply doesn’t allow anything else. State doesn’t come into being anywhere on the side; it arises exclusively from update processing a message. So the history of the state is identical to the list of messages – and the question “when did this happen?” has an answer again: at message number 34, between 33 and 35.

What is remarkable about this shape is how little it has to do with the Elm language. Model, update, view – that is a fold over a sequence of events plus a projection. Both are concepts that exist in every language. The question that wouldn’t let go of me: How much of the clarity remains if you drop the compiler and voluntarily rebuild the shape in JavaScript?

The rebuild: actions as a stream#

The core of the rebuild fits into a few lines. Every user interaction becomes a value on a stream, and a single update function folds this stream into the model. In the repository, this sits behind a small API of init, update, view and subscriptions – here is the raw form without the wrapping:

import Rx from 'rx'

// every user interaction becomes a value on this stream
const actions$ = new Rx.Subject()

function update (model, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: model.count + 1 }
    case 'DECREMENT':
      return { count: model.count - 1 }
    case 'TICK':
      return { count: model.count + action.step }
    default:
      return model
  }
}

// fold the action history into the current model
const model$ = actions$
  .startWith({ type: 'INIT' })
  .scan(update, { count: 0 })

A side note on the choice of library: the prototype uses the classic rx package, that is, version 4 with onNext and dispose. RxJS 5 is available as a release candidate and will align the names with the ES Observable proposals (next, unsubscribe), but for an experiment I wanted the stable version, whose operator documentation is complete. That changes nothing about the concept – method chains on observables work the same in both worlds.

The decisive operator is scan. If you know reduce over arrays, you almost know scan: it is the same fold, except that it doesn’t wait for a finished array but emits the intermediate result for every new element. reduce folds a closed list into a final value. scan folds a list that never ends – and that is exactly what a user interface is: a sequence of events without an end point. The model at a point in time is nothing but the fold of all actions up to that point in time. This one insight is half the article: state is the left fold over the event history.

React only renders#

In this setup, React gets a deliberately boring role: it projects the current model into the DOM and reports interactions back to the action stream. No fetch in componentDidMount, no state logic in handlers – the component follows the model$ stream and nothing else:

import React from 'react'

class CounterView extends React.Component {
  componentDidMount () {
    // the view follows the model stream, nothing else
    this.subscription = model$.subscribe(model => this.setState({ model }))
  }

  componentWillUnmount () {
    this.subscription.dispose()
  }

  render () {
    if (!this.state) return null
    const { count } = this.state.model
    return (
      <div>
        <span>{count}</span>
        <button onClick={() => actions$.onNext({ type: 'INCREMENT' })}>+</button>
        <button onClick={() => actions$.onNext({ type: 'DECREMENT' })}>-</button>
      </div>
    )
  }
}

That setState still shows up here is not a break in style, but the handover point: somewhere the stream has to flow into React’s render cycle, and in React 15, setState simply is the door. What matters is that it is the only place where setState occurs – as a bridge, not as state management. In the repository, this bridge comes in two variants: once as a higher-order component withElmish for composition with stateless functional components, once as a base class ReactComponent that you inherit from, overriding init, update and view.

At this point, by the way, the rebuild deliberately departs from Elm and from Redux: it keeps state per component instead of in a central store. Every “smart” component gets its own small Elm loop, “dumb” components remain stateless functions. Whether that is a good idea depends on how things are cut – for the collection of examples in the repository (counter, form validation, optimistic UI updates, an ordering process as a long-running saga stream), it was pleasant, because each example lives on its own. For a large application, I would ask the question again.

Side effects as streams at the edge#

The most interesting part is the one counter examples like to leave out: What happens to everything that doesn’t come from a click? Timers, HTTP responses, server push. In Elm, those are subscriptions and tasks. In the rebuild, they are – of course – observables. The subscriptions function receives a command from init or update and responds with a stream whose values end up as messages in update again:

const stop$ = actions$.filter(action => action.type === 'INTERVAL_STOP')

function subscriptions (cmd) {
  switch (cmd) {
    case 'INTERVAL_START':
      return Rx.Observable
        .interval(1000)
        .map(() => ({ type: 'TICK', step: 1 }))
        .takeUntil(stop$)
  }
}

The runtime layer subscribes to this stream itself; the component never calls subscribe. This keeps side effects where they belong: at the edge, as separate streams that you compose with the same operators as everything else. takeUntil ends the timer declaratively, merge combines several sources, filter splits a stream into substreams. The lifecycle of a side effect is no longer special logic, but a data flow expression.

This also reveals a real difference from Elm, not a rebuilt one: Elm subscriptions only know next – the next message comes, nothing else. Errors and completion pass through update as ordinary message content, and for chained asynchronous effects there are tasks with andThen. An Rx observable, on the other hand, carries three signals in its contract: next, error, complete. A stream can fail, and a stream can be done – both are part of the type, not convention. For things like AJAX long polling against a CouchDB change feed or EventSource push (both included as examples in the repository), this is the more natural description.

The entire cycle, as a picture:

flowchart LR
  U[User event] --> A["actions$ (stream)"]
  SUB["subscriptions:<br/>interval, HTTP, push"] --> A
  A --> S["scan(update, initialModel)"]
  S --> M["model$ (stream)"]
  M --> V["React view<br/>renders the model"]
  V --> U

One direction, one cycle. Everything that happens happens as a value on a stream – and is therefore observable, filterable, loggable. An actions$.subscribe(console.log) in the right place replaces a lot of debugger sessions.

Redux, Elm, RxJS – the same idea three times#

If you have read this far and know Redux, you saw the punchline long ago: update is a reducer. (model, action) => model and (state, action) => state are the same signature with different names. That is no coincidence – Dan Abramov has never hidden the fact that Redux distills the Elm Architecture for JavaScript. The difference lies in what each variant of the idea enforces and what it merely recommends.

Redux does the fold with less math and more convention: a store instead of a model stream, dispatch instead of onNext, middleware instead of operator chains. That reducers stay pure and side effects stay outside is written in the documentation – nobody can enforce it. In return, you get an ecosystem: DevTools with time travel, bindings, conventions that a team can adopt without discussion. Interestingly, redux-observable is growing into a middleware right now that brings Rx streams back into Redux as a side effect layer – actions in, actions out, observable operators in between. So the two worlds are converging anyway.

Elm enforces the shape in the compiler. There is no way to sneak state past update, no forgotten mutation, no unhandled message variant – the type check finds them. That is the hardest variant, but also the most unforgiving one: you only get the guarantees together with the language.

And RxJS? RxJS makes explicit something that stays implicit in both of the others: time. An observable is a sequence of values on a timeline, and the operators talk about it openly – debounce negotiates intervals, takeUntil an end, scan history. In Redux, time is a side effect of the dispatch order; in Elm, the runtime hides it. In the Rx rebuild, it is in the code. Once you have seen that “state” is just the current result of a fold over the timeline, you read Redux code differently afterward too. CycleJS, by the way, takes the same thought even further: there, the entire application is a function from streams to streams, replacing React including rendering. And if you want to see the opposite school, you will find it in MobX, which doesn’t ban mutation but makes it observable – a different contract, a different discussion.

What building it yourself teaches – and what it doesn’t#

After a few weeks with the prototype and its sixteen examples, my verdict is split in two. I learned more than from any blog article about Redux, and specifically things that apply regardless of the library:

  • Understanding state as a fold makes failure patterns explainable: not “the state is wrong”, but “this sequence of actions produces this model” – a verifiable statement.
  • A single direction in the data flow is not aesthetics, but the reason you can still read the system once it has grown.
  • Side effects are manageable when they have an explicit lifecycle – whether that is called a task, a subscription or an observable.
  • update as a pure function is trivially testable; the test for the delayed counter in the repository needs neither a DOM nor a browser.

What building it yourself is not: a production replacement. The warning in the README is there out of conviction. Everything that makes an architecture hold up in everyday work is missing – well-thought-out error handling across component boundaries, tools, documentation beyond a README, and above all: other people who know the code. A framework that one person built over a few evenings is a learning machine, not a foundation. If you want the Elm Architecture in JavaScript in production, take Redux and get conventions and a community along with it; if you want the guarantees, take Elm and pay with the language switch. The rebuild in between has exactly one purpose: understanding why both work.

Add to that an observation from the building itself: the temptation to turn the proof of concept into a real framework “just quickly” is enormous. Every example suggests another abstraction, every abstraction another configuration point. I deliberately pushed back – minimally invasive, React rendering plus Rx composition, not one layer more than necessary. That is a lesson too: the distance between “instructive prototype” and “bad framework” is about two weekends.

The bottom line#

Why does this shape age so well? Because it makes almost no assumptions about its environment. Model, update, view – that requires neither a language nor a library nor a rendering technique. React 15 can be replaced by something else tomorrow, rx version 4 by version 5, and the architecture stays the same, because it consists of two ingredients that are older than the web: a fold and a projection. In this field, frameworks come and go fast enough that I don’t mean this as a platitude, but as a selection criterion.

And the question from the beginning – when did this happen? – always has an answer in this shape. The event history is not a by-product you reconstruct with logging, but the primary data structure of the application. Everything else, the model included, is derived from it. When, in future reviews, I sit in front of a UI whose state nobody can explain anymore, this will be my first suggestion: not more tools, but one direction.

Further reading#

Revised and translated from German with the help of AI.