• Stars
    star
    3,032
  • Rank 14,088 (Top 0.3 %)
  • Language
    JavaScript
  • Created almost 9 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Observables for ECMAScript

ECMAScript Observable

This proposal introduces an Observable type to the ECMAScript standard library. The Observable type can be used to model push-based data sources such as DOM events, timer intervals, and sockets. In addition, observables are:

  • Compositional: Observables can be composed with higher-order combinators.
  • Lazy: Observables do not start emitting data until an observer has subscribed.

Example: Observing Keyboard Events

Using the Observable constructor, we can create a function which returns an observable stream of events for an arbitrary DOM element and event type.

function listen(element, eventName) {
    return new Observable(observer => {
        // Create an event handler which sends data to the sink
        let handler = event => observer.next(event);

        // Attach the event handler
        element.addEventListener(eventName, handler, true);

        // Return a cleanup function which will cancel the event stream
        return () => {
            // Detach the event handler from the element
            element.removeEventListener(eventName, handler, true);
        };
    });
}

We can then use standard combinators to filter and map the events in the stream, just like we would with an array.

// 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])
}

Note: The "filter" and "map" methods are not included in this proposal. They may be added in a future version of this specification.

When we want to consume the event stream, we subscribe with an observer.

let subscription = commandKeys(inputElement).subscribe({
    next(val) { console.log("Received key command: " + val) },
    error(err) { console.log("Received an error: " + err) },
    complete() { console.log("Stream complete") },
});

The object returned by subscribe will allow us to cancel the subscription at any time. Upon cancelation, the Observable's cleanup function will be executed.

// After calling this function, no more events will be sent
subscription.unsubscribe();

Motivation

The Observable type represents one of the fundamental protocols for processing asynchronous streams of data. It is particularly effective at modeling streams of data which originate from the environment and are pushed into the application, such as user interface events. By offering Observable as a component of the ECMAScript standard library, we allow platforms and applications to share a common push-based stream protocol.

Implementations

Running Tests

To run the unit tests, install the es-observable-tests package into your project.

npm install es-observable-tests

Then call the exported runTests function with the constructor you want to test.

require("es-observable-tests").runTests(MyObservable);

API

Observable

An Observable represents a sequence of values which may be observed.

interface Observable {

    constructor(subscriber : SubscriberFunction);

    // Subscribes to the sequence with an observer
    subscribe(observer : Observer) : Subscription;

    // Subscribes to the sequence with callbacks
    subscribe(onNext : Function,
              onError? : Function,
              onComplete? : Function) : Subscription;

    // Returns itself
    [Symbol.observable]() : Observable;

    // Converts items to an Observable
    static of(...items) : Observable;

    // Converts an observable or iterable to an Observable
    static from(observable) : Observable;

}

interface Subscription {

    // Cancels the subscription
    unsubscribe() : void;

    // A boolean value indicating whether the subscription is closed
    get closed() : Boolean;
}

function SubscriberFunction(observer: SubscriptionObserver) : (void => void)|Subscription;

Observable.of

Observable.of creates an Observable of the values provided as arguments. The values are delivered synchronously when subscribe is called.

Observable.of("red", "green", "blue").subscribe({
    next(color) {
        console.log(color);
    }
});

/*
 > "red"
 > "green"
 > "blue"
*/

Observable.from

Observable.from converts its argument to an Observable.

  • If the argument has a Symbol.observable method, then it returns the result of invoking that method. If the resulting object is not an instance of Observable, then it is wrapped in an Observable which will delegate subscription.
  • Otherwise, the argument is assumed to be an iterable and the iteration values are delivered synchronously when subscribe is called.

Converting from an object which supports Symbol.observable to an Observable:

Observable.from({
    [Symbol.observable]() {
        return new Observable(observer => {
            setTimeout(() => {
                observer.next("hello");
                observer.next("world");
                observer.complete();
            }, 2000);
        });
    }
}).subscribe({
    next(value) {
        console.log(value);
    }
});

/*
 > "hello"
 > "world"
*/

let observable = new Observable(observer => {});
Observable.from(observable) === observable; // true

Converting from an iterable to an Observable:

Observable.from(["mercury", "venus", "earth"]).subscribe({
    next(value) {
        console.log(value);
    }
});

/*
 > "mercury"
 > "venus"
 > "earth"
*/

Observer

An Observer is used to receive data from an Observable, and is supplied as an argument to subscribe.

All methods are optional.

interface Observer {

    // Receives the subscription object when `subscribe` is called
    start(subscription : Subscription);

    // Receives the next value in the sequence
    next(value);

    // Receives the sequence error
    error(errorValue);

    // Receives a completion notification
    complete();
}

SubscriptionObserver

A SubscriptionObserver is a normalized Observer which wraps the observer object supplied to subscribe.

interface SubscriptionObserver {

    // Sends the next value in the sequence
    next(value);

    // Sends the sequence error
    error(errorValue);

    // Sends the completion notification
    complete();

    // A boolean value indicating whether the subscription is closed
    get closed() : Boolean;
}

More Repositories

1

proposals

Tracking ECMAScript Proposals
17,177
star
2

ecma262

Status, process, and documents for ECMA-262
HTML
14,437
star
3

proposal-pipeline-operator

A proposal for adding a useful pipe operator to JavaScript.
HTML
7,330
star
4

proposal-pattern-matching

Pattern matching syntax for ECMAScript
HTML
5,297
star
5

proposal-optional-chaining

HTML
4,951
star
6

proposal-type-annotations

ECMAScript proposal for type syntax that is erased - Stage 1
JavaScript
4,067
star
7

proposal-temporal

Provides standard objects and functions for working with dates and times.
HTML
3,077
star
8

proposal-decorators

Decorators for ES6 classes
2,604
star
9

proposal-record-tuple

ECMAScript proposal for the Record and Tuple value types. | Stage 2: it will change!
HTML
2,404
star
10

test262

Official ECMAScript Conformance Test Suite
JavaScript
2,073
star
11

proposal-dynamic-import

import() proposal for JavaScript
HTML
1,859
star
12

proposal-bind-operator

This-Binding Syntax for ECMAScript
1,736
star
13

proposal-class-fields

Orthogonally-informed combination of public and private fields proposals
HTML
1,720
star
14

proposal-async-await

Async/await for ECMAScript
HTML
1,575
star
15

proposal-object-rest-spread

Rest/Spread Properties for ECMAScript
HTML
1,496
star
16

proposal-shadowrealm

ECMAScript Proposal, specs, and reference implementation for Realms
HTML
1,353
star
17

proposal-nullish-coalescing

Nullish coalescing proposal x ?? y
HTML
1,232
star
18

proposal-iterator-helpers

Methods for working with iterators in ECMAScript
HTML
1,202
star
19

proposal-top-level-await

top-level `await` proposal for ECMAScript (stage 4)
HTML
1,082
star
20

proposal-partial-application

Proposal to add partial application to ECMAScript
HTML
1,002
star
21

proposal-do-expressions

Proposal for `do` expressions
HTML
990
star
22

agendas

TC39 meeting agendas
JavaScript
952
star
23

proposal-binary-ast

Binary AST proposal for ECMAScript
944
star
24

proposal-built-in-modules

HTML
886
star
25

proposal-async-iteration

Asynchronous iteration for JavaScript
HTML
854
star
26

proposal-explicit-resource-management

ECMAScript Explicit Resource Management
JavaScript
671
star
27

proposal-operator-overloading

JavaScript
598
star
28

proposal-string-dedent

TC39 Proposal to remove common leading indentation from multiline template strings
HTML
588
star
29

proposal-bigint

Arbitrary precision integers in JavaScript
HTML
561
star
30

proposal-set-methods

Proposal for new Set methods in JS
HTML
557
star
31

ecmascript_simd

SIMD numeric type for EcmaScript
JavaScript
536
star
32

proposal-import-attributes

Proposal for syntax to import ES modules with assertions
HTML
523
star
33

proposal-slice-notation

HTML
515
star
34

proposal-change-array-by-copy

Provides additional methods on Array.prototype and TypedArray.prototype to enable changes on the array by returning a new copy of it with the change.
HTML
508
star
35

ecma402

Status, process, and documents for ECMA 402
HTML
506
star
36

notes

TC39 meeting notes
JavaScript
496
star
37

proposal-class-public-fields

Stage 2 proposal for public class fields in ECMAScript
HTML
489
star
38

proposal-uuid

UUID proposal for ECMAScript (Stage 1)
JavaScript
462
star
39

proposal-iterator.range

A proposal for ECMAScript to add a built-in Iterator.range()
JavaScript
459
star
40

proposal-throw-expressions

Proposal for ECMAScript 'throw' expressions
JavaScript
425
star
41

proposal-module-expressions

HTML
417
star
42

proposal-UnambiguousJavaScriptGrammar

413
star
43

proposal-array-grouping

A proposal to make grouping of array items easier
HTML
407
star
44

proposal-async-context

Async Context for JavaScript
HTML
406
star
45

proposal-weakrefs

WeakRefs
HTML
403
star
46

proposal-decimal

Built-in decimal datatype in JavaScript
HTML
398
star
47

proposal-error-cause

TC39 proposal for accumulating errors
HTML
378
star
48

proposal-ecmascript-sharedmem

Shared memory and atomics for ECMAscript
HTML
376
star
49

proposal-cancelable-promises

Former home of the now-withdrawn cancelable promises proposal for JavaScript
Shell
376
star
50

proposal-relative-indexing-method

A TC39 proposal to add an .at() method to all the basic indexable classes (Array, String, TypedArray)
HTML
351
star
51

proposal-first-class-protocols

a proposal to bring protocol-based interfaces to ECMAScript users
348
star
52

proposal-global

ECMAScript Proposal, specs, and reference implementation for `global`
HTML
346
star
53

proposal-private-methods

Private methods and getter/setters for ES6 classes
HTML
345
star
54

proposal-numeric-separator

A proposal to add numeric literal separators in JavaScript.
HTML
327
star
55

proposal-private-fields

A Private Fields Proposal for ECMAScript
HTML
320
star
56

proposal-object-from-entries

TC39 proposal for Object.fromEntries
HTML
317
star
57

proposal-promise-allSettled

ECMAScript Proposal, specs, and reference implementation for Promise.allSettled
HTML
314
star
58

tc39.github.io

Get involved in specifying JavaScript
HTML
313
star
59

proposal-module-declarations

JavaScript Module Declarations
HTML
311
star
60

proposal-regex-escaping

Proposal for investigating RegExp escaping for the ECMAScript standard
JavaScript
309
star
61

proposal-await.ops

Introduce await.all / await.race / await.allSettled / await.any to simplify the usage of Promises
HTML
307
star
62

proposal-logical-assignment

A proposal to combine Logical Operators and Assignment Expressions
HTML
302
star
63

proposal-export-default-from

Proposal to add `export v from "mod";` to ECMAScript.
HTML
297
star
64

proposal-promise-finally

ECMAScript Proposal, specs, and reference implementation for Promise.prototype.finally
HTML
278
star
65

proposal-asset-references

Proposal to ECMAScript to add first-class location references relative to a module
268
star
66

proposal-cancellation

Proposal for a Cancellation API for ECMAScript
HTML
262
star
67

proposal-json-modules

Proposal to import JSON files as modules
HTML
254
star
68

proposal-string-replaceall

ECMAScript proposal: String.prototype.replaceAll
HTML
254
star
69

proposal-promise-with-resolvers

HTML
241
star
70

proposal-export-ns-from

Proposal to add `export * as ns from "mod";` to ECMAScript.
HTML
240
star
71

proposal-intl-relative-time

`Intl.RelativeTimeFormat` specification [draft]
HTML
215
star
72

proposal-flatMap

proposal for flatten and flatMap on arrays
HTML
215
star
73

proposal-ses

Draft proposal for SES (Secure EcmaScript)
HTML
214
star
74

proposal-structs

JavaScript Structs: Fixed Layout Objects
211
star
75

ecmarkup

An HTML superset/Markdown subset source format for ECMAScript and related specifications
TypeScript
201
star
76

proposal-json-parse-with-source

Proposal for extending JSON.parse to expose input source text.
HTML
200
star
77

proposal-promise-any

ECMAScript proposal: Promise.any
HTML
198
star
78

proposal-decorators-previous

Decorators for ECMAScript
HTML
184
star
79

proposal-smart-pipelines

Old archived draft proposal for smart pipelines. Go to the new Hack-pipes proposal at js-choi/proposal-hack-pipes.
HTML
181
star
80

proposal-defer-import-eval

A proposal for introducing a way to defer evaluate of a module
HTML
174
star
81

proposal-array-filtering

A proposal to make filtering arrays easier
HTML
171
star
82

proposal-optional-chaining-assignment

`a?.b = c` proposal
168
star
83

proposal-array-from-async

Draft specification for a proposed Array.fromAsync method in JavaScript.
HTML
167
star
84

proposal-extractors

Extractors for ECMAScript
JavaScript
166
star
85

proposal-upsert

ECMAScript Proposal, specs, and reference implementation for Map.prototype.upsert
HTML
165
star
86

proposal-ptc-syntax

Discussion and specification for an explicit syntactic opt-in for Tail Calls.
HTML
164
star
87

how-we-work

Documentation of how TC39 operates and how to participate
161
star
88

proposal-collection-methods

HTML
160
star
89

proposal-Array.prototype.includes

Spec, tests, reference implementation, and docs for ESnext-track Array.prototype.includes
HTML
157
star
90

proposal-error-stacks

ECMAScript Proposal, specs, and reference implementation for Error.prototype.stack / System.getStack
HTML
155
star
91

proposal-promise-try

ECMAScript Proposal, specs, and reference implementation for Promise.try
HTML
154
star
92

proposal-hashbang

#! for JS
HTML
148
star
93

proposal-resizablearraybuffer

Proposal for resizable array buffers
HTML
145
star
94

proposal-import-meta

import.meta proposal for JavaScript
HTML
145
star
95

proposal-intl-segmenter

Unicode text segmentation for ECMAScript
HTML
145
star
96

proposal-extensions

Extensions proposal for ECMAScript
HTML
143
star
97

proposal-seeded-random

Proposal for an options argument to be added to JS's Math.random() function, and some options to start it with.
HTML
143
star
98

proposal-intl-duration-format

141
star
99

proposal-accessible-object-hasownproperty

Object.hasOwn() proposal for ECMAScript
HTML
134
star
100

proposal-regexp-unicode-property-escapes

Proposal to add Unicode property escapes `\p{…}` and `\P{…}` to regular expressions in ECMAScript.
HTML
132
star