DEV Community

What if everything in your app was a stream?

Most JavaScript frameworks assume that your application state is a handful of variables and objects that you mutate over time. But what if you modelled every piece of state—clicks, form values, API responses—as a stream? This is the core idea behind stream-oriented programming.

In this article, we’ll explore how treating events as streams can simplify your code and make it easier to scale. We’ll use Rimmel.js to bind streams directly to the DOM, so there’s no need for event listeners or clean-up functions. Then we’ll build a simple click counter to illustrate the paradigm.

Why streams?

A stream is a sequence of values over time. You can create them from user input, timers or network requests. The beauty is that they’re infinitely composable—combine multiple streams into a new stream and the contract remains the same. This makes it trivial to build larger pieces of functionality.

Rimmel: connecting streams to the DOM

Rimmel’s reactive markup (RML) lets you embed streams directly in your HTML. When a stream emits a value, Rimmel updates the corresponding part of the DOM. There’s no virtual DOM; updates happen only when data changes.

Hello world: click counter

import { BehaviorSubject, scan } from 'rxjs';
import { rml } from 'rimmel';

// stream of click counts
const clicks = new BehaviorSubject(0);

// update count on each click
const count = clicks.pipe(scan(n => n + 1));

const template = rml`
  <button onclick="${clicks}">Click me</button>
  You clicked <span>${count}</span> times.
`;

document.body.innerHTML = template;
Enter fullscreen mode Exit fullscreen mode

Every time the button is clicked, the increment stream emits a new value. Rimmel binds the input stream to the button’s onclick and the output to the <span>, updating the count. You don’t need to manually attach event listeners or manage state.

Try it yourself: StackBlitz demo.

Next steps: In upcoming posts we’ll build a reactive to-do list using ObservableTypes and explore plugins with TOPS. If you’ve built something cool with streams, share it in the comments!

Top comments (0)