Topic

  • HarmonyOS

更新时间不可用

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

信息

Topic 只存在于 Stream Channel。所以用户在使用相关特性之前,需要先创建一个 StreamChannel 对象实例。

想要了解 Topic 的更多特性,可以查看:

joinTopic

接口描述

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

信息

  • 当前 RTM 支持单客户端在同一个 Stream Channel 中同时加入 8 个 Topic。
  • 在执行此操作之前,用户需要首先创建 StreamChannel 对象实例,并调用 join 方法加入频道,详见频道。

成功加入 Topic 后,订阅该 Topic 并添加事件监听的用户会收到 REMOTE_JOIN 类型的 topic 事件通知。详见事件监听。

接口方法

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

TypeScript
async joinTopic(topicName: string, options?: JoinTopicOptions): Promise<JoinTopicResponse>
参数类型是否必填默认值描述
topicNamestring必填-Topic 名称。
optionsJoinTopicOptions选填{}加入 Topic 选项。
表格内容超出当前宽度,可横向滚动查看更多列。

JoinTopicOptions 数据类型包含以下属性:

属性类型是否必填默认值描述
qosRtmMessageQos选填UNORDERED定义此 Topic 中传输数据是否保序。详见 RtmMessageQos。
priorityRtmMessagePriority选填NORMAL定义此 Topic 中传输数据的优先级(相比于同频道中的其他 Topic)。详见 RtmMessagePriority。
metastring选填''加入 Topic 时携带的其他辅助信息。
syncWithMediaboolean选填false此 Topic 中发送的数据是否与共频道的 RTC 音视频数据流实现数据同步(时间戳对齐)。
表格内容超出当前宽度,可横向滚动查看更多列。

返回值

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

JoinTopicResponse 数据结构如下:

属性类型描述
timestampnumber操作的时间戳(保留字段,供未来使用)。
topicNamestringTopic 名称。
表格内容超出当前宽度,可横向滚动查看更多列。

基本用法

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

用户发送的消息在传输的过程中会被 TLS 加密,数据链路加密默认开启且无法关闭。用户也可以在出初始化的时候开启端侧加密,以获得更高的数据安全等级,详见初始配置。

接口方法

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

TypeScript
async publishTopicMessage(topicName: string, message: string | Uint8Array, options?: TopicMessageOptions): Promise<PublishTopicMessageResponse>
参数类型是否必填默认值描述
topicNamestring必填-Topic 名称。
messagestring | Uint8Array必填-消息负载。可以是字符串或二进制数据。
optionsTopicMessageOptions选填{}消息选项。
表格内容超出当前宽度,可横向滚动查看更多列。

TopicMessageOptions 数据类型包含以下属性:

属性类型是否必填默认值描述
sendTsnumber选填0消息发送时间戳。只有在 joinTopic 中设置 syncWithMedia = true 时,该参数才有效,SDK 会根据此时间戳与 RTC 音视频数据流进行数据同步。
customTypestring选填''用户自定义字段。仅支持 String 型。
表格内容超出当前宽度,可横向滚动查看更多列。

返回值

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

PublishTopicMessageResponse 数据结构如下:

属性类型描述
timestampnumber操作的时间戳(保留字段,供未来使用)。
topicNamestringTopic 名称。
表格内容超出当前宽度,可横向滚动查看更多列。

基本用法

示例 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

接口描述

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

成功调用该方法后,订阅该频道并开启事件监听的用户会收到 REMOTE_LEAVE 类型的 topic 事件通知,详见 事件监听。

接口方法

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

TypeScript
async leaveTopic(topicName: string): Promise<LeaveTopicResponse>
参数类型是否必填默认值描述
topicNamestring必填-Topic 名称。
表格内容超出当前宽度,可横向滚动查看更多列。

返回值

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

LeaveTopicResponse 数据结构如下:

属性类型描述
timestampnumber操作的时间戳(保留字段,供未来使用)。
topicNamestringTopic 名称。
表格内容超出当前宽度,可横向滚动查看更多列。

基本用法

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 方法订阅该频道中 Topic 的消息发布者。

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

同一个用户在同一个频道中最多只能同时订阅 50 个 Topic,且每个 Topic 中最多只能订阅 64 个消息发布者。详见 API 调用限制。

接口方法

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

TypeScript
async subscribeTopic(topicName: string, options?: TopicOptions): Promise<SubscribeTopicResponse>
参数类型是否必填默认值描述
topicNamestring必填-Topic 名称。
optionsTopicOptions选填{}订阅 Topic 选项。
表格内容超出当前宽度,可横向滚动查看更多列。

TopicOptions 数据类型包含以下属性:

属性类型是否必填默认值描述
usersstring[]选填[]需要订阅的消息发布者(Publisher)的 UserId 列表,如果不设置,则默认随机订阅不超过 64 个用户。
表格内容超出当前宽度,可横向滚动查看更多列。

返回值

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

SubscribeTopicResponse 数据结构如下:

属性类型描述
timestampnumber操作的时间戳(保留字段,供未来使用)。
topicNamestringTopic 名称。
succeedUsersstring[]订阅成功的用户列表。
failedUsersstring[]订阅失败的用户列表。
表格内容超出当前宽度,可横向滚动查看更多列。

基本用法

示例 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

接口描述

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

接口方法

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

TypeScript
async unsubscribeTopic(topicName: string, options?: TopicOptions): Promise<UnsubscribeTopicResponse>
参数类型是否必填默认值描述
topicNamestring必填-Topic 名称。
optionsTopicOptions选填{}取消订阅 Topic 选项。
表格内容超出当前宽度,可横向滚动查看更多列。

TopicOptions 数据类型包含以下属性:

属性类型是否必填默认值描述
usersstring[]选填[]需要取消订阅的消息发布者(Publisher)的 UserId 列表,如果不设置,则默认随机取消订阅不超过 64 个用户。
表格内容超出当前宽度,可横向滚动查看更多列。

返回值

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

UnsubscribeTopicResponse 数据结构如下:

属性类型描述
timestampnumber操作的时间戳(保留字段,供未来使用)。
topicNamestringTopic 名称。
表格内容超出当前宽度,可横向滚动查看更多列。

基本用法

示例 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);
  }
}