Search code examples
javascriptobservablecombinators

What does this mean in the Observable TC-39 proposal?


In the TC-39 Observable API proposal I see:

Compositional: Observables can be composed with higher-order combinators.

A combinator is a function that can be used to combine two (or more?) logic pieces into single, more useful construct.

So what does the above quote mean in the context of observables?


Solution

  • Combinators, in the context of Observables, refer to the functions (usually attached to Observable.prototype, in the implementations I've seen) that allow you to transform one kind of Observable into another. There's a good example a little bit further down in the proposal:

    // Return an observable of special key down commands
    function commandKeys(element) {
        let keyCommands = { "38": "up", "40": "down" };
    
        return listen(element, "keydown")
            .filter(event => event.keyCode in keyCommands)
            .map(event => keyCommands[event.keyCode])
    }
    

    In this example, filter and map are the combinators - they work in a similar fashion to the functions of the same name on Array.prototype. The important thing to note is that, similarly to the array functions, they always return a new Observable - they do not mutate the existing one. This is useful, because it means that further combinators could be chained on to the result of commandKeys if necessary.