# Topic (/zh-CN/api-reference/rtm/harmonyos/topic)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

Topic 是 Stream Channel 中的数据流管理机制。用户可以在 Stream Channel 中利用此特性进行数据流的订阅、分发、事件通知等。

:::info[信息]
Topic 只存在于 Stream Channel。所以用户在使用相关特性之前，需要先创建一个 `StreamChannel` 对象实例。
:::

想要了解 Topic 的更多特性，可以查看：

- [Topic](/zh-CN/realtime-media/rtm/build/channels-and-topics/topics/topic-basic)

## joinTopic [#jointopic]

### 接口描述 [#接口描述]

加入 Topic 的目的在于注册成为该 Topic 的消息发布者之一，从而让用户具备发送消息的能力。是否执行该操作都不影响该用户是否成为该 Topic 的订阅者。

:::info[信息]
- 当前 RTM 支持单客户端在同一个 Stream Channel 中同时加入 8 个 Topic。
- 在执行此操作之前，用户需要首先创建 `StreamChannel` 对象实例，并调用 `join` 方法加入频道，详见[频道](/zh-CN/realtime-media/rtm/build/channels-and-topics/channel-basic)。
:::

成功加入 Topic 后，订阅该 Topic 并添加事件监听的用户会收到 `REMOTE_JOIN` 类型的 `topic` 事件通知。详见[事件监听](/zh-CN/api-reference/rtm/harmonyos/configuration#事件监听)。

### 接口方法 [#接口方法]

你可以通过以下方式调用 `joinTopic` 方法：

```typescript
async joinTopic(topicName: string, options?: JoinTopicOptions): Promise<JoinTopicResponse>
```

| 参数 | 类型 | 是否必填 | 默认值 | 描述 |
| --- | --- | --- | --- | --- |
| `topicName` | string | 必填 | - | Topic 名称。 |
| `options` | `JoinTopicOptions` | 选填 | `{}` | 加入 Topic 选项。 |

`JoinTopicOptions` 数据类型包含以下属性：

|      属性       |     类型     | 是否必填 | 默认值               |    描述    |
| ------------ | -------------- | ----- | ---------------- | ----------- |
|  `qos`   | `RtmMessageQos` |   选填   | `UNORDERED` |                  定义此 Topic 中传输数据是否保序。详见 [`RtmMessageQos`](/zh-CN/api-reference/rtm/harmonyos/enumv#messageqos)。                  |
|   `priority`    |  `RtmMessagePriority`  |   选填   | `NORMAL`    | 定义此 Topic 中传输数据的优先级（相比于同频道中的其他 Topic）。详见 [`RtmMessagePriority`](/zh-CN/api-reference/rtm/harmonyos/enumv#messagepriority)。 |
|   `meta`   |    string    |   选填   | `''`                    |         加入 Topic 时携带的其他辅助信息。          |
| `syncWithMedia` |   boolean    |   选填   | `false`              |        此 Topic 中发送的数据是否与共频道的 RTC 音视频数据流实现数据同步（时间戳对齐）。        |

### 返回值 [#返回值]

该方法返回一个 Promise，成功时 resolve 并返回 `JoinTopicResponse` 对象，失败时 reject 并抛出 `RtmError` 异常。

`JoinTopicResponse` 数据结构如下：

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `timestamp` | number | 操作的时间戳（保留字段，供未来使用）。 |
| `topicName` | string | Topic 名称。 |

### 基本用法 [#基本用法]

```typescript
import { RtmClient, RtmError, RtmMessageQos, RtmMessagePriority } from '@shengwang/rtm-full';
import type { JoinTopicOptions } from '@shengwang/rtm-full';

// Create and join stream channel
const streamChannel = rtmClient.createStreamChannel('game-room');
await streamChannel.join({ token: 'your_token' });

// Join a topic with options
const options: JoinTopicOptions = {
  qos: RtmMessageQos.ORDERED,
  priority: RtmMessagePriority.HIGH,
  meta: 'game-chat',
  syncWithMedia: false
};

try {
  const response = await streamChannel.joinTopic('chat', options);
  console.log('Joined topic:', response.topicName);
} catch (error) {
  if (error instanceof RtmError) {
    console.error('Join topic failed:', error.errorCode, error.reason);
  }
}
```

## publishTopicMessage [#publishtopicmessage]

### 接口描述 [#接口描述-1]

`publishTopicMessage` 方法用于向 Topic 发送消息，频道中订阅此 Topic 及此消息发布者的用户会在 100 毫秒内收到此消息。调用 `publishTopicMessage` 方法需要用户首先加入 Stream Channel 并且通过调用 `joinTopic` 方法注册成为该 Topic 的消息发布者。

用户发送的消息在传输的过程中会被 TLS 加密，数据链路加密默认开启且无法关闭。用户也可以在出初始化的时候开启端侧加密，以获得更高的数据安全等级，详见[初始配置](/zh-CN/api-reference/rtm/harmonyos/configuration)。

### 接口方法 [#接口方法-1]

你可以通过以下方式调用 `publishTopicMessage` 方法：

```typescript
async publishTopicMessage(topicName: string, message: string | Uint8Array, options?: TopicMessageOptions): Promise<PublishTopicMessageResponse>
```

| 参数 | 类型 | 是否必填 | 默认值 | 描述 |
| --- | --- | --- | --- | --- |
| `topicName` | string | 必填 | - | Topic 名称。 |
| `message` | string \| Uint8Array | 必填 | - | 消息负载。可以是字符串或二进制数据。 |
| `options` | `TopicMessageOptions` | 选填 | `{}` | 消息选项。 |

`TopicMessageOptions` 数据类型包含以下属性：

|     属性     |  类型  | 是否必填 | 默认值 | 描述          |
| --------- | --- | ----- | --- | -------- |
|   `sendTs`   |  number  |   选填   |  `0`   | 消息发送时间戳。只有在 `joinTopic` 中设置 `syncWithMedia = true` 时，该参数才有效，SDK 会根据此时间戳与 RTC 音视频数据流进行数据同步。 |
| `customType` | string |   选填   |   `''`    | 用户自定义字段。仅支持 String 型。     |

### 返回值 [#返回值-1]

该方法返回一个 Promise，成功时 resolve 并返回 `PublishTopicMessageResponse` 对象，失败时 reject 并抛出 `RtmError` 异常。

`PublishTopicMessageResponse` 数据结构如下：

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `timestamp` | number | 操作的时间戳（保留字段，供未来使用）。 |
| `topicName` | string | Topic 名称。 |

### 基本用法 [#基本用法-1]

示例 1：向指定频道发送 String 消息

```typescript
import { RtmClient, RtmError } from '@shengwang/rtm-full';
import type { TopicMessageOptions } from '@shengwang/rtm-full';

// Create and join stream channel
const streamChannel = rtmClient.createStreamChannel('game-room');
await streamChannel.join({ token: 'your_token' });
await streamChannel.joinTopic('chat');

// Publish string message
const options: TopicMessageOptions = {
  customType: 'Text'
};

try {
  const response = await streamChannel.publishTopicMessage('chat', 'hello world', options);
  console.log('Published to topic:', response.topicName);
} catch (error) {
  if (error instanceof RtmError) {
    console.error('Publish failed:', error.errorCode, error.reason);
  }
}
```

示例 2：向指定频道发送 Byte 消息

```typescript
import { RtmClient, RtmError } from '@shengwang/rtm-full';
import type { TopicMessageOptions } from '@shengwang/rtm-full';

// Create binary message
const message = new Uint8Array([0x00, 0x01, 0x02, 0x03, 0x04]);

const options: TopicMessageOptions = {
  customType: 'ByteArray'
};

try {
  const response = await streamChannel.publishTopicMessage('data', message, options);
  console.log('Published binary message to topic:', response.topicName);
} catch (error) {
  if (error instanceof RtmError) {
    console.error('Publish failed:', error.errorCode, error.reason);
  }
}
```

## leaveTopic [#leavetopic]

### 接口描述 [#接口描述-2]

当你不再需要向某个 Topic 发布消息，你可以调用 `leaveTopic` 方法取消注册为该 Topic 的消息发布者，从而释放资源。该方法不影响你是否订阅该 Topic，也不影响其他用户对该 Topic 的任何操作。

成功调用该方法后，订阅该频道并开启事件监听的用户会收到 `REMOTE_LEAVE` 类型的 `topic` 事件通知，详见 [事件监听](/zh-CN/api-reference/rtm/harmonyos/configuration#事件监听)。

### 接口方法 [#接口方法-2]

你可以通过以下方式调用 `leaveTopic` 方法：

```typescript
async leaveTopic(topicName: string): Promise<LeaveTopicResponse>
```

| 参数 | 类型 | 是否必填 | 默认值 | 描述 |
| --- | --- | --- | --- | --- |
| `topicName` | string | 必填 | - | Topic 名称。 |

### 返回值 [#返回值-2]

该方法返回一个 Promise，成功时 resolve 并返回 `LeaveTopicResponse` 对象，失败时 reject 并抛出 `RtmError` 异常。

`LeaveTopicResponse` 数据结构如下：

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `timestamp` | number | 操作的时间戳（保留字段，供未来使用）。 |
| `topicName` | string | Topic 名称。 |

### 基本用法 [#基本用法-2]

```typescript
import { RtmClient, RtmError } from '@shengwang/rtm-full';

// Create and join stream channel
const streamChannel = rtmClient.createStreamChannel('game-room');
await streamChannel.join({ token: 'your_token' });
await streamChannel.joinTopic('chat');

// Leave topic
try {
  const response = await streamChannel.leaveTopic('chat');
  console.log('Left topic:', response.topicName);
} catch (error) {
  if (error instanceof RtmError) {
    console.error('Leave topic failed:', error.errorCode, error.reason);
  }
}
```

## subscribeTopic [#subscribetopic]

### 接口描述 [#接口描述-3]

加入频道后，你可以调用 `subscribeTopic` 方法订阅该频道中 Topic 的消息发布者。

`subscribeTopic` 为增量方法。例如，第一次调用该方法时，订阅消息发布者列表为 `[UserA, UserB]`，第二次调用该方法时，订阅消息发布者列表为 `[UserB, UserC]`，则最后成功订阅的结果是 `[UserA, UserB, UserC]`。

同一个用户在同一个频道中最多只能同时订阅 50 个 Topic，且每个 Topic 中最多只能订阅 64 个消息发布者。详见 [API 调用限制](/zh-CN/realtime-media/rtm/reference/usage-limits-and-errors/api-limits)。

### 接口方法 [#接口方法-3]

你可以通过以下方式调用 `subscribeTopic` 方法：

```typescript
async subscribeTopic(topicName: string, options?: TopicOptions): Promise<SubscribeTopicResponse>
```

| 参数 | 类型 | 是否必填 | 默认值 | 描述 |
| --- | --- | --- | --- | --- |
| `topicName` | string | 必填 | - | Topic 名称。 |
| `options` | `TopicOptions` | 选填 | `{}` | 订阅 Topic 选项。 |

`TopicOptions` 数据类型包含以下属性：

|  属性   |        类型         | 是否必填 | 默认值 | 描述            |
| ---- | ---------------- | ----- | --- | --------- |
| `users` | string[] |   选填   |   `[]`    | 需要订阅的消息发布者（Publisher）的 `UserId` 列表，如果不设置，则默认随机订阅不超过 64 个用户。 |

### 返回值 [#返回值-3]

该方法返回一个 Promise，成功时 resolve 并返回 `SubscribeTopicResponse` 对象，失败时 reject 并抛出 `RtmError` 异常。

`SubscribeTopicResponse` 数据结构如下：

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `timestamp` | number | 操作的时间戳（保留字段，供未来使用）。 |
| `topicName` | string | Topic 名称。 |
| `succeedUsers` | string[] | 订阅成功的用户列表。 |
| `failedUsers` | string[] | 订阅失败的用户列表。 |

### 基本用法 [#基本用法-3]

示例 1：订阅 Topic 中指定的消息发布者

```typescript
import { RtmClient, RtmError } from '@shengwang/rtm-full';
import type { TopicOptions } from '@shengwang/rtm-full';

// Create and join stream channel
const streamChannel = rtmClient.createStreamChannel('game-room');
await streamChannel.join({ token: 'your_token' });

// Subscribe to specific users
const options: TopicOptions = {
  users: ['UserA', 'UserB']
};

try {
  const response = await streamChannel.subscribeTopic('chat', options);
  console.log('Subscribed to topic:', response.topicName);
  console.log('Succeed users:', response.succeedUsers);
  console.log('Failed users:', response.failedUsers);
} catch (error) {
  if (error instanceof RtmError) {
    console.error('Subscribe topic failed:', error.errorCode, error.reason);
  }
}
```

示例 2：随机订阅 Topic 中的 64 个消息发布者

```typescript
import { RtmClient, RtmError } from '@shengwang/rtm-full';

// Create and join stream channel
const streamChannel = rtmClient.createStreamChannel('game-room');
await streamChannel.join({ token: 'your_token' });

// Subscribe to random users (up to 64)
try {
  const response = await streamChannel.subscribeTopic('chat');
  console.log('Subscribed to topic:', response.topicName);
  console.log('Succeed users:', response.succeedUsers);
} catch (error) {
  if (error instanceof RtmError) {
    console.error('Subscribe topic failed:', error.errorCode, error.reason);
  }
}
```

## unsubscribeTopic [#unsubscribetopic]

### 接口描述 [#接口描述-4]

如果你对某个 Topic 不再感兴趣，或者不再需要订阅 Topic 中的一个或多个消息发布者，你可以调用 `unsubscribeTopic` 方法取消订阅该 Topic 或取消订阅该 Topic 中指定的消息发布者。

### 接口方法 [#接口方法-4]

你可以通过以下方式调用 `unsubscribeTopic` 方法：

```typescript
async unsubscribeTopic(topicName: string, options?: TopicOptions): Promise<UnsubscribeTopicResponse>
```

| 参数 | 类型 | 是否必填 | 默认值 | 描述 |
| --- | --- | --- | --- | --- |
| `topicName` | string | 必填 | - | Topic 名称。 |
| `options` | `TopicOptions` | 选填 | `{}` | 取消订阅 Topic 选项。 |

`TopicOptions` 数据类型包含以下属性：

|  属性   |        类型         | 是否必填 | 默认值 | 描述            |
| ---- | ---------------- | ----- | --- | --------- |
| `users` | string[] |   选填   |   `[]`    | 需要取消订阅的消息发布者（Publisher）的 `UserId` 列表，如果不设置，则默认随机取消订阅不超过 64 个用户。 |

### 返回值 [#返回值-4]

该方法返回一个 Promise，成功时 resolve 并返回 `UnsubscribeTopicResponse` 对象，失败时 reject 并抛出 `RtmError` 异常。

`UnsubscribeTopicResponse` 数据结构如下：

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `timestamp` | number | 操作的时间戳（保留字段，供未来使用）。 |
| `topicName` | string | Topic 名称。 |

### 基本用法 [#基本用法-4]

示例 1：取消订阅 Topic 中指定的消息发布者

```typescript
import { RtmClient, RtmError } from '@shengwang/rtm-full';
import type { TopicOptions } from '@shengwang/rtm-full';

// Create and join stream channel
const streamChannel = rtmClient.createStreamChannel('game-room');
await streamChannel.join({ token: 'your_token' });

// Unsubscribe from specific users
const options: TopicOptions = {
  users: ['UserA', 'UserB']
};

try {
  const response = await streamChannel.unsubscribeTopic('chat', options);
  console.log('Unsubscribed from topic:', response.topicName);
} catch (error) {
  if (error instanceof RtmError) {
    console.error('Unsubscribe topic failed:', error.errorCode, error.reason);
  }
}
```

示例 2：随机取消订阅 Topic 中的 64 个消息发布者

```typescript
import { RtmClient, RtmError } from '@shengwang/rtm-full';

// Create and join stream channel
const streamChannel = rtmClient.createStreamChannel('game-room');
await streamChannel.join({ token: 'your_token' });

// Unsubscribe from random users (up to 64)
try {
  const response = await streamChannel.unsubscribeTopic('chat');
  console.log('Unsubscribed from topic:', response.topicName);
} catch (error) {
  if (error instanceof RtmError) {
    console.error('Unsubscribe topic failed:', error.errorCode, error.reason);
  }
}
```
