DEV Community


Posted on

Observables, naïve implementation

Following my previous post on streams, one can wonder what are streams fundamentaly ?

At the most basic, a stream is nothing more than an object that can be observed, they are in fact obervables.

Many objects can be observed, the particularity of streams is that they are composable observables.

Let's see if we can implement a very simple observable.

Our requirements are:

  1. use only function (no classes, no proxies...)
  2. passed value must be stored
  3. invocation must return the stored value
  4. no globals

How can a function can store a value?, that seems a little strange. A stream seems not to be a basic function...

The following function does not store anything.
When you invoke it without argument, it simply returns nothing.

function stream (value) {
    let storedvalue = value
    return storedvalue

What can we do then? We will use a particular feature of Javascript called closure.

Using closures is simple, the explanation on how they works internally is beyond my knowledege.

So here it is :

function Stream (value) {
  let storedvalue = value
  function stream (newvalue) {
    if (arguments.length) {
      storedvalue = newvalue
    return storedvalue
  return stream

let s = Stream(5)


You can test it here stream

In Javascript, functions are first class citizens. They are treated like any other objects.
They can be passed as arguments to other functions, they can be returned from functions.

Closures allow returned functions to 'capture' a variable defined outer it, magic :-)

This function fullfill our requirements, in the next post, we will see how to "react" whenever a stream is "feeded" by a new value...

Thanks for reading

Top comments (0)