大网数据广告活动
Web 标准与前端开发

Observable: Observable() constructor

· 52CE 我爱测

The **`Observable()`** constructor creates a new Observable object whose values and lifecycle are controlled by a callback.

Observable API

The Observable() constructor creates a new Observable object whose values and lifecycle are controlled by a callback.

Syntax

new Observable(callback)

Parameters

  • callback
    • : A function that starts producing values when a subscription starts. Its return value is ignored. The function is called with the following argument:
      • subscriber
        • : A Subscriber used to send values with Subscriber.next, signal completion or an error with Subscriber.complete or Subscriber.error, and register cleanup with Subscriber.addTeardown.

Return value

A new Observable object.

Description

The constructor does not call callback immediately. It runs synchronously when the first observer subscribes. Additional observers share the same Subscriber until it becomes inactive. A later subscription starts the callback again with a new subscriber. See Creating an observable for the subscription lifecycle.

[!NOTE] This shared-subscription behavior may change. A proposal to give each observer its own Subscriber would make each subscription start a separate execution instead of reusing an active subscription.

If callback throws an exception, it is passed to subscriber.error(). An async callback's returned promise is ignored, so its rejection is not handled automatically. Handle asynchronous errors explicitly and forward them with subscriber.error() while the subscriber is active.

Examples

Observing element size

This example reports a resizable panel's dimensions using a custom observable backed by ResizeObserver. Clicking Stop unsubscribes and disconnects the observer. Click Restart to observe the panel again. See Observing element size for a more detailed explanation.

<div id="panel">Drag the corner to resize.</div>
<p></p>
<button>Stop</button>
<button id="restart" disabled>Restart</button>
#panel {
  width: 200px;
  height: 100px;
  resize: both;
  overflow: auto;
  border: 1px solid;
}
const panel = document.querySelector("#panel");
const output = document.querySelector("p");
const btn = document.querySelector("button");

const sizes = new Observable((subscriber) => {
  const observer = new ResizeObserver(([entry]) => {
    subscriber.next(entry.contentRect);
  });
  observer.observe(panel);
  subscriber.addTeardown(() => observer.disconnect());
});

const restart = document.querySelector("#restart");

function start() {
  restart.disabled = true;
  sizes.takeUntil(btn.when("click")).subscribe({
    next({ width, height }) {
      output.textContent = `${Math.round(width)} × ${Math.round(height)} pixels`;
    },
    complete() {
      restart.disabled = false;
    },
  });
}

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

constructor-resize

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。