AtomicXCore 框架中的 BarrageState 模块,为您的直播应用快速集成功能丰富、性能卓越的弹幕系统。
BarrageState 为您的直播应用提供了一套完整的弹幕解决方案,核心功能包括:liveID 绑定的 BarrageState 实例,并且监听 messageList 来接收最新的全量弹幕消息列表。import { useEffect } from 'react';import { useBarrageState } from 'react-native-tuikit-atomic-x/lib/module/atomic-x/state/BarrageState';// 通过 liveID 获取 BarrageState 的实例const { messageList } = useBarrageState(liveID);// 监听 messageList 的实时变更,用于驱动 UI 更新useEffect(() => {console.log(messageList);}, [messageList]);
sendTextMessage 方法向直播间内的所有用户广播一条纯文本消息。import { useBarrageState } from 'react-native-tuikit-atomic-x/lib/module/atomic-x/state/BarrageState';// 通过 liveID 获取 BarrageState 的实例const { sendTextMessage } = useBarrageState(liveID);const sendMessage = () => {sendTextMessage({liveID: liveID, // 当前直播间的 liveIDtext: 'xxx', // 您想要发送的弹幕onSuccess: () => {console.log('弹幕发送成功');},onError: (error) => {console.log('弹幕发送失败', error);},});};
参数 | 类型 | 描述 |
liveID | string | 当前直播间的 liveID。 |
text | string | 要发送的文本内容。 |
onSuccess | Function | 发送成功的回调。 |
onError | Function | 发送失败的回调。 |
import { useBarrageState } from 'react-native-tuikit-atomic-x/lib/module/atomic-x/state/BarrageState';// 通过 liveID 获取 BarrageState 的实例const { sendCustomMessage } = useBarrageState(liveID);// 发送一条自定义弹幕,例如用于发送礼物const sendGiftMessage = (giftID, giftCount) => {// 1. 定义一个能识别业务的 IDconst businessID = 'live_gift';// 2. 将业务数据编码为 JSON 字符串const giftData = { gift_id: giftID, gift_count: giftCount };// 3. 调用核心 API 发送自定义消息sendCustomMessage({liveID: liveID, // 当前直播间的 liveIDbusinessID,data: JSON.stringify(giftData),onSuccess: () => {console.log('礼物消息发送成功');},onError: (error) => {console.log('礼物消息发送失败', error);},});};
参数 | 类型 | 描述 |
liveID | string | 当前直播间的 liveID。 |
businessID | string | 业务唯一标识符,例如 "live_gift",用于接收端区分不同的自定义消息。 |
data | string | 业务数据,通常为 JSON 格式的字符串。 |
onSuccess | Function | 发送成功的回调。 |
onError | Function | 发送失败的回调。 |
import { useBarrageState } from 'react-native-tuikit-atomic-x/lib/module/atomic-x/state/BarrageState';// 通过 liveID 获取 BarrageState 的实例const { appendLocalTip } = useBarrageState(liveID);const showWelcomeMessage = (user) => {appendLocalTip({liveID: liveID, // 当前直播间的 liveIDmessage: {textContent: `欢迎 ${user.userName} 进入直播间!`,sender: {userID: user.userID || '',userName: user.userName || '',avatarURL: user.avatarURL || '',},messageType: 0,sequence: Math.floor(Date.now() / 1000),timestampInSecond: Math.floor(Date.now() / 1000),liveID: liveID,},onSuccess: () => {console.log('插入本地消息成功');},onError: (error) => {console.log('插入本地消息失败', error);},});};
参数 | 类型 | 描述 |
liveID | string | 当前语聊房的 liveID。 |
message | object | 要在本地插入的消息对象。SDK 会将此消息对象追加到 BarrageState 的 messageList 中。 |
onSuccess | Function | 添加本地消息成功的回调。 |
onError | Function | 添加本地消息失败的回调。 |
LiveAudienceState 中的 disableSendMessage 接口来实现对指定用户的禁言或解禁。此状态会被持久化,即使用户重新进入直播间,禁言状态依然有效。import { useLiveAudienceState } from 'react-native-tuikit-atomic-x/lib/module/atomic-x/state/LiveAudienceState';// 通过 liveID 获取 LiveAudienceState 的实例const { disableSendMessage } = useLiveAudienceState(liveID);// 定义要操作的用户 ID 和禁言状态const userIdToMute = 'user_id_to_be_muted'; // 想要操作的用户 userIDconst shouldDisable = true; // true 为禁言, false 为解禁// 调用接口执行操作const toggleMuteUser = () => {disableSendMessage({liveID: liveID, // 当前直播间 liveIDuserID: userIdToMute,isDisable: shouldDisable,onSuccess: () => {console.log(`${shouldDisable ? '禁言' : '解禁'}用户 ${userIdToMute} 成功`);},onError: (error) => {console.log('操作失败', error);},});};
参数 | 类型 | 描述 |
liveID | string | 当前语聊房的 liveID。 |
userID | string | 想要操作的用户 userID。 |
isDisable | boolean | 是否禁言用户。 |
onSuccess | Function | 禁言成功的回调。 |
onError | Function | 禁言失败的回调。 |
LiveListState 的 updateLiveInfo 更新直播间信息来实现。import { useLiveListState } from 'react-native-tuikit-atomic-x/lib/module/atomic-x/state/LiveListState';import { LiveInfoModifyFlag } from 'react-native-tuikit-atomic-x/lib/module/atomic-x/state/LiveListState/types';// 1. 获取 LiveListState 的实例const { updateLiveInfo, currentLive } = useLiveListState();// 2. 获取当前直播间信息,并修改全体禁言状态const isCurrentlyMuted = currentLive?.isMessageDisable || false;// 3. 调用更新接口,并指定修改的标志位const toggleMuteAll = () => {updateLiveInfo({liveInfo: { liveID: currentLive?.liveID, isMessageDisable: !isCurrentlyMuted },modifyFlagList: [LiveInfoModifyFlag.IS_MESSAGE_DISABLE],onSuccess: () => {console.log(`${!isCurrentlyMuted ? '全体禁言' : '取消禁言'}成功`);},onError: (error) => {console.log('操作失败', error);},});};
参数 | 类型 | 描述 |
liveInfo | object | liveID 是必填项,其余为需要更新的直播状态。 |
modifyFlagList | LiveInfoModifyFlag[] | 需要更新的直播信息标记位数组。 |
onSuccess | Function | 更新直播信息成功的回调。 |
onError | Function | 更新直播信息失败的回调。 |
BarrageState 构建弹幕功能后,本章将指导您如何处理更复杂的业务场景,确保它能在真实、复杂的高并发直播场景下,依然为用户提供流畅、稳定的体验。本章将围绕两个核心业务场景,为您提供明确的优化方案和代码示例。import { useEffect, useRef, useState } from 'react';import { useBarrageState } from 'react-native-tuikit-atomic-x/lib/module/atomic-x/state/BarrageState';// 通过 liveID 获取 BarrageState 的实例const { messageList } = useBarrageState(liveID);// UI 展示数据const [displayMessageList, setDisplayMessageList] = useState([]);// ===== 节流配置 =====const THROTTLE_INTERVAL = 300; // 300毫秒节流阈值const latestMessageListRef = useRef([]);const throttleTimerRef = useRef(null);const lastFlushTimeRef = useRef(0);useEffect(() => {if (!messageList) return;// 缓存最新的完整列表(不触发渲染)latestMessageListRef.current = messageList;const now = Date.now();const timeSinceLastFlush = now - lastFlushTimeRef.current;// 如果距离上次刷新已经超过阈值,立即执行刷新if (timeSinceLastFlush >= THROTTLE_INTERVAL) {setDisplayMessageList([...latestMessageListRef.current]);lastFlushTimeRef.current = now;} else if (!throttleTimerRef.current) {// 只有没有定时器时才设,避免设置多个定时器const remainingTime = THROTTLE_INTERVAL - timeSinceLastFlush;throttleTimerRef.current = setTimeout(() => {setDisplayMessageList([...latestMessageListRef.current]);lastFlushTimeRef.current = Date.now();throttleTimerRef.current = null;}, remainingTime);}// 300ms 内的中间更新会被跳过,定时器到期时用最新数据刷新}, [messageList]);// 组件卸载时清理定时器useEffect(() => {return () => {if (throttleTimerRef.current) {clearTimeout(throttleTimerRef.current);}};}, []);// 使用 displayMessageList 驱动 UI 渲染// <FlatList data={displayMessageList} ... />
messageList 会在长时间直播中无限增长,即使 UI 层做了节流,数据层持有的这个巨大数组也会持续占用内存,最终导致应用闪退。SDK 的全量列表后,只取最新的500条(或您定义的其他数量)来更新 UI。import { useEffect, useState } from 'react';import { useBarrageState } from 'react-native-tuikit-atomic-x/lib/module/atomic-x/state/BarrageState';// 通过 liveID 获取 BarrageState 的实例const { messageList } = useBarrageState(liveID);// UI 展示数据const [displayMessageList, setDisplayMessageList] = useState([]);// ===== 消息窗口配置(只保留最新N条消息)=====const MAX_MESSAGES_COUNT = 500;// 裁剪消息列表:只保留最新的 MAX_MESSAGES_COUNT 条消息const trimMessageList = (messages) => {if (messages.length > MAX_MESSAGES_COUNT) {console.warn(`[BarrageList] 消息数量超过限制 ${MAX_MESSAGES_COUNT},已删除 ${messages.length - MAX_MESSAGES_COUNT} 条最早消息`);return messages.slice(messages.length - MAX_MESSAGES_COUNT);}return messages;};// 监听 messageList 变化,裁剪后更新 UIuseEffect(() => {if (!messageList) return;setDisplayMessageList(trimMessageList([...messageList]));}, [messageList]);// 使用 displayMessageList 驱动 UI 渲染// <FlatList data={displayMessageList} ... />
sendCustomMessage 来实现的。BarrageState 不会限制您的业务想象力。{ "type": "colored_text", "text": "这是一条彩色弹幕!", "color": "#FF5733" }
sendCustomMessage 的 data 参数发送出去。businessID 可以设置为一个能代表您业务的唯一标识,例如 "barrage_style_v1"。messageType 是否为 'CUSTOM' 以及 businessID 是否匹配。如果匹配,则解析 data 字符串(通常是解析 JSON),根据解析出的数据(例如 color、text)来渲染您的自定义 UI 样式。sendTextMessage 方法有成功和失败回调。请检查回调返回的结果是成功还是失败。如果失败,错误信息会明确指出问题所在(例如“您已被禁言”、“网络错误”等)。barrageState 的订阅发生在该 liveID 对应的直播开始之后。如果在加入直播房间之前就开始监听,可能会错过部分消息。BarrageState 实例、加入直播房间、以及发送消息时使用的 liveID 完全一致,包括大小写。AtomicXCore 支持拉取历史弹幕消息,但这需要您在服务端控制台进行一项简单的配置。配置完成后,SDK 会自动处理后续的一切,您无需编写额外的代码。
AtomicXCore 底层会自动拉取配置的历史消息数量。这些历史消息会和实时消息一样,通过 BarrageState的订阅通道推送到 UI 层。应用会像接收实时弹幕一样,自然地接收并展示这些历史弹幕。文档反馈