Skip to content

Lifecycle API ​

Core lifecycle methods: instance creation, initialization, join/leave classroom, event system.

Typical Flow ​

typescript
import { TencentClassroom, TEvent } from '@tencent-classroom/sdk';

const classroom = new TencentClassroom({ language: 'en', debug: true });
await classroom.init();
await classroom.joinClass({ classId: 123, userId: 'u1', token: 'xxx' });
// ... operations ...
await classroom.leaveClass();
await classroom.destroy();

API Reference ​

Constructor ​

Create a new SDK instance.

构造后实例自动注册为静态单例 TencentClassroom.instance; The new instance is automatically registered as TencentClassroom.instance; if an instance already exists, the new one replaces it.

构造 ≠ 初始化:构造仅注册内置模块,不做网络或 SDK 初始化。 Construction ≠ initialization: the constructor only registers built-in modules. You must call init() before using any other API.

ParameterTypeDescription
config?ClassroomConfig = {}SDK configuration (all fields optional)

Returns: TencentClassroom

Example:

ts
const classroom = new TencentClassroom({
  language: 'zh-CN',         // 界面语言 / UI language
  debug: true,               // 开启调试日志 / Enable debug logging
  board: { domId: 'board' }, // 白板容器 / Whiteboard container
  behavior: {
    autoLoadDefaultDocument: true, // 进房后自动加载默认课件
  },
});

state ​

Read-only reactive state proxy.

All fields end with $. (BehaviorSubject semantics: subscribers receive the current value immediately on subscribe).

Example:

ts
classroom.state.classStatus$.subscribe(s => updateUI(s));
const currentStatus = classroom.state.classStatus$.get();

instance ​

Get the current SDK instance (static singleton).

在 new TencentClassroom() 之后的任意位置都可通过此属性访问, Accessible from anywhere after new TencentClassroom() — no need to pass the instance through props/context.

Throws if new TencentClassroom() has not been called yet.


checkEnvironment() ​

Check whether the current runtime environment meets the minimum requirements for the classroom.

Aggregates the following critical capability checks (failure of any one results in isSupported=false):

  1. 浏览器环境 / Browser environment — 排除 SSR / Node 等场景
  2. 安全上下文 / Secure context — HTTPS 或 localhost(getUserMedia 必需)
  3. mediaDevices — navigator.mediaDevices.getUserMedia 是否可用
  4. WebRTC — TRTC.isSupported()(或自定义 RTC 适配器的等价实现)

Recommended to call after init() and before joinClass(); show a UI prompt when not supported.

与设备权限/可用性检查的边界:本方法只验证"环境/能力",不触发摄像头/麦克风授权弹窗。 Boundary: this method validates capability only; it does NOT trigger camera/mic permission prompts. Use getCameraList() / getMicrophoneList() for device enumeration & permission.

Returns: Promise<TResult<EnvironmentCheckResult>>

Example:

ts
const env = await classroom.checkEnvironment();
if (!env.ok) {
  toast.error(env.message);
  return;
}
if (!env.data.isSupported) {
  if (env.data.reasons?.includes('InsecureContext')) {
    toast.error('请使用 HTTPS 访问本页面');
  } else if (env.data.reasons?.includes('WebRTCUnsupported')) {
    toast.error('当前浏览器不支持音视频,请使用 Chrome 85+ 或 Edge 86+');
  } else {
    toast.error('当前环境不支持课堂运行');
  }
  return;
}
await classroom.joinClass({ classId, userId, token });

destroy() ​

Destroy the engine instance, releasing all resources (TRTC / IM / Logger, etc.).

The static singleton TencentClassroom.instance is cleared after this call.

destroy() automatically triggers leaveClass() — no need to call it manually first.

Returns: Promise<TResult<void>>


init() ​

Initialize the engine (must be called before joinClass).

Internally: starts Logger Worker → initializes all built-in modules in dependency order → applies behavior config.

Returns: Promise<TResult<void>>

Example:

ts
const result = await classroom.init();
if (!result.ok) {
  console.error('[init failed]', result.detail);
  showToast(result.message);
  return;
}

joinClass() ​

Join a classroom (full join flow: school info → class info → IM → TRTC → board → permission → history).

进房进度通过 state.joinProgress$ Signal 实时推送, Join progress is pushed via state.joinProgress$ Signal and TEvent.JOIN_PROGRESS_CHANGED event.

ParameterTypeDescription
paramsJoinParams进房参数(classId / userId / token 必填)

Returns: Promise<TResult<void>>

Example:

ts
const result = await classroom.joinClass({
  classId: 123456,
  userId: 'teacher_001',
  token: 'biz-token-from-server',
  role: 'teacher',           // 可选,SDK 会根据课堂配置自动推断
});
if (!result.ok) {
  showToast(result.message);
  return;
}

leaveClass() ​

Leave the classroom actively (exits TRTC / IM / board, stops heartbeat, resets state).

Returns: Promise<TResult<void>>

Example:

ts
await classroom.leaveClass();
await classroom.destroy(); // 通常在 leaveClass 之后调用 destroy

off() ​

Unsubscribe from an event.

ParameterTypeDescription
eventEEvent name
listener?PublicClassroomEvents[E]要移除的回调。不传则移除该事件的所有监听器。

Returns: void


on() ​

Subscribe to an event (persists until manually unsubscribed).

Use TEvent.XXX constants instead of string literals for compile-time safety and IDE autocomplete.

⚠️ 仅可订阅 PublicClassroomEvents 中的事件; SDK 内部模块通信事件(如 streamUpdate / imCmdMessage / 各类内部信号)已被屏蔽。 Only events in PublicClassroomEvents can be subscribed; SDK-internal events are filtered out. For stream list awareness, subscribe to Signals in classroom.state rather than events.

ParameterTypeDescription
eventEEvent name (use TEvent.XXX constants)
listenerPublicClassroomEvents[E]回调函数,参数类型由 PublicClassroomEvents 精确推导

Returns: () => void

Example:

ts
// 监听课堂开始 / Listen for class start
const off = classroom.on(TEvent.CLASS_START, () => console.log('课堂开始'));
off(); // 业务结束后取消 / Unsubscribe when done

// 监听被踢出 / Listen for kick-out
classroom.on(TEvent.KICK_OUT, ({ reason, message }) => {
  console.warn('kicked out:', reason);
  showAlert(message);
});

// 监听进房进度 / Listen for join progress
classroom.on(TEvent.JOIN_PROGRESS_CHANGED, ({ progress }) => {
  if (progress === JoinProgress.Completed) showSuccessUI();
});

once() ​

Subscribe to an event for a single occurrence (auto-unsubscribes after first trigger).

ParameterTypeDescription
eventEEvent name (use TEvent.XXX constants)
listenerPublicClassroomEvents[E]Callback, automatically removed after first invocation

Returns: () => void

Example:

ts
classroom.once(TEvent.JOIN_CLASS, (classInfo) => {
  console.log('进房成功,课堂名:', classInfo.className);
});

waitFor() ​

Wait for an event to fire and return a Promise (fires once, async version of once).

Ideal for sequential async flows like "join, then do next step" — cleaner than on/once.

ParameterTypeDescription
eventEEvent name
timeout?number超时毫秒数(不传则永不超时)。超时后 Promise reject,需自行 catch。

Returns: Promise<Parameters<PublicClassroomEvents\[E\]>\[0\]>

Example:

ts
// 等待进房完成 / Wait for join to complete
const classInfo = await classroom.waitFor(TEvent.JOIN_CLASS);

// 设置 10 秒超时保护 / 10-second timeout
try {
  await classroom.waitFor(TEvent.JOIN_CLASS, 10000);
} catch {
  console.error('进房超时 / Join timed out');
}

classInfo ​

Current classroom info — available after joinClass(), null after leaveClass().

Equivalent to state.classInfo$.get() — a synchronous shorthand.


i18n ​

国际化引擎,用于语言切换、词条覆盖、注册自定义语言。 i18n engine — language switching, message overrides, custom locale registration.


initialized ​

Whether the engine has been successfully initialized (i.e., init() returned ok=true).


platform ​

Platform detector — provides information about the current runtime environment.


version ​

SDK version string (instance property, same as TencentClassroom.VERSION).


VERSION ​

SDK version string (static property).

Example:

ts
TencentClassroom.VERSION // => '2.0.0'