Observable: from() static method

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The from() static method of the Observable interface returns an observable converted from a promise, iterable, or async iterable; existing observables are returned unchanged.

Syntax

js
Observable.from(value)

Parameters

value

An object to convert to an observable: an Observable, a Promise, an iterable object, or an async iterable object.

Return value

An Observable. If value is already an observable, it is returned unchanged. Otherwise, a new observable is returned that emits values from value when subscribed to.

Exceptions

TypeError

Thrown if value cannot be converted to an observable. Primitive values, including strings, are not accepted.

Description

The conversion checks for an existing observable first, then an async iterable, then an iterable, and finally a promise.

  • A promise contributes its fulfillment value, followed by completion. A rejection becomes an error.
  • An iterable contributes its values synchronously, followed by completion when the iterator is exhausted.
  • An async iterable contributes its values as they become available, followed by completion when the iterator is exhausted.

Errors while iterating become errors in the observable.

Calling from() does not subscribe to the returned observable. However, converting an existing promise does not defer the work that created it. Unsubscribing also does not cancel that work. If the promise rejects after the subscriber becomes inactive, the error is reported to the global object.

Many methods that take observables, such as Observable.takeUntil(), implicitly convert the argument to observables, so you can pass promises, iterables, and async iterables as well.

Examples

Converting a synchronous iterable

Calling from() creates the observable without starting iteration. In this example, subscribing delivers all array values and the completion notification before subscribe() returns:

js
const observable = Observable.from([1, 2, 3]);

console.log("Before subscribing");
observable.subscribe({
  next(value) {
    console.log(value);
  },
  complete() {
    console.log("Complete");
  },
});
console.log("After subscribing");

// Before subscribing
// 1
// 2
// 4
// Complete
// After subscribing

Converting a promise

This example converts a promise for the first button click into an observable. It displays the click's coordinates, then a completion message. Click Restart after the stream ends to try again.

js
const btn = document.querySelector("button");
const output = document.querySelector("p");
const restart = document.querySelector("#restart");

function start() {
  restart.disabled = true;
  output.textContent = "Waiting for a click";
  const firstClick = btn.when("click").first();

  Observable.from(firstClick).subscribe({
    next(event) {
      output.textContent = `${event.clientX},${event.clientY}`;
    },
    complete() {
      restart.disabled = false;
      output.textContent += " — Complete.";
    },
  });
}

restart.when("click").subscribe(start);
start();

Converting an async iterable

This example logs chunks of text from a fetched file. The decoded ReadableStream is an async iterable; each chunk may contain part of a line or several lines.

js
const response = await fetch("/data.txt");
if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}

const textStream = response.body.pipeThrough(new TextDecoderStream());

Observable.from(textStream).subscribe({
  next(chunk) {
    console.log(chunk);
  },
  error(error) {
    console.error("Reading failed:", error);
  },
  complete() {
    console.log("Stream complete");
  },
});

Specifications

Specification
Observable
# dom-observable-from

Browser compatibility

See also