tc39/proposal-observable

Name: proposal-observable

Owner: Ecma TC39

Description: Observables for ECMAScript

Created: 2015-05-01 05:00:12.0

Updated: 2018-05-24 07:57:54.0

Pushed: 2017-10-16 16:23:45.0

Homepage: https://tc39.github.io/proposal-observable/

Size: 476

Language: JavaScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

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:

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.

tion 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.

eturn an observable of special key down commands
tion 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.

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.

fter calling this function, no more events will be sent
cription.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.

install es-observable-tests

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

ire("es-observable-tests").runTests(MyObservable);
API
Observable

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

rface 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;



rface Subscription {

// Cancels the subscription
unsubscribe() : void;

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


tion 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.

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



red"
green"
blue"

Observable.from

Observable.from converts its argument to an Observable.

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

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



hello"
world"


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

Converting from an iterable to an Observable:

rvable.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.

rface 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.

rface 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;


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.