添加事件监听

  • Flutter

更新时间

了解实时消息 RTM 中添加事件监听相关内容的适用场景、配置步骤、实现要点和注意事项。

如需收到消息和事件通知,你需要先实现事件监听程序,然后订阅或者加入你想要接收消息或事件通知的频道。

添加事件监听

RTM 采用统一入口的方式处理消息和事件通知,每一种消息和事件通知都有对应的事件处理程序入口,你可以在其中实现自己的业务处理逻辑:

Dart
rtmClient.addListener(
    // Handle message event
    message: (MessageEvent event) {
        const channelType = event.channelType;                  // The channel type need to be "STREAM" or "MESSAGE".
        const channelName = event.channelName;                  // The name of the channel that this message comes from.
        const topicName = event.channelTopic;                   // (Stream channel only) The name of the topic that this message comes from.
        const messageType = event.messageType;                  // The message type need to be "STRING" or "BINARY".
        const customType = event.customType;                    // User defined type.
        const publisher = event.publisher;                      // Message publisher.
        const message = event.message;                          // Message payload.
        const timestamp = event.timestamp;                      // Message send timestamp.
    },
    // Handle presence event
    presence: (PresenceEvent event) {
        const action = event.type;                              // Which action it is ,should be one of 'SNAPSHOT'、'INTERVAL'、'JOIN'、'LEAVE'、'TIMEOUT、'STATE_CHANGED'、'OUT_OF_SERVICE'.
        const channelType = event.channelType;                  // Which channel type it is, Should be "STREAM" or "MESSAGE".
        const channelName = event.channelName;                  // Which channel does this event come from
        const publisher = event.publisher;                      // Who trigger this event
        const states = event.stateItems;                        // User state payload, only for stateChanged event
        const interval = event.interval;                        // Interval payload, only for interval event
        const snapshot = event.snapshot;                        // Snapshot payload, only for snapshot event
        const timestamp = event.timestamp;                      // event trigger timestamp.
    },
   // Handle topic event
    topic: (TopicEvent event) {
        const action = event.type;                              // Which action it is ,should be one of 'SNAPSHOT'、'JOIN'、'LEAVE'.
        const channelName = event.channelName;                  // Which channel does this event comes from
        const publisher = event.publisher;                      // Who trigger this event
        const topicInfos = event.topicInfos;                    // Topic information payload
        const timestamp = event.timestamp;                      // event trigger timestamp.
    },
    // Handle storage event
    storage: (StorageEvent event) {
        const channelType = event.channelType;                  // Which channel type it is, Should be "STREAM" or "MESSAGE".
        const target = event.target;                            // Which channel or who trigger this event
        const storageType = event.storageType;                  // Which category the event is, should be 'USER'、'CHANNEL'
        const action = event.eventType;                         // Which action it is ,should be one of "SNAPSHOT"、"SET"、"REMOVE"、"UPDATE" or "NONE"
        const data = event.data;                                // 'USER_METADATA' or 'CHANNEL_METADATA' payload
        const timestamp = event.timestamp;                      // event trigger timestamp.
    },
    // Handle lock event
    lock: (LockEvent event) {
        const channelType = event.channelType;                  // Which channel type it is, Should be "STREAM" or "MESSAGE".
        const channelName = event.channelName;                  // Which channel does this event come from
        const action = event.evenType;                          // Which action it is ,should be one of 'SET'、'REMOVED'、'ACQUIRED'、'RELEASED'、'EXPIRED'、'SNAPSHOT'
        const lockDetailList = event.lockDetailList;            // lock event payload
        const timestamp = event.timestamp;                      // event trigger timestamp.
    },
    // Handle link state event
    linkState: (LinkStateEvent event) {
        const currentState = event.currentState;                // What is current link state
        const previousState = event.previousState;              // What is previous link state
        const serviceType = event.serviceType;                  // Which service type it is, Should be "stream" or "message".
        const operation = event.operation;                      // Which operation trigger this state changed
        const reason = event.reason;                            // Which reason trigger this state changed
        const affectedChannels = event.affectedChannels;        // Which channels are affected
        const unrestoredChannels = event.unrestoredChannels;    // Which channels are unrestored
        const isResumed = event.isResumed;
        const timestamp = event.timestamp;                      // event trigger timestamp.
    },
    // Handle token event
    token : (TokenEvent event) {
        const channelName = event.channelName;                  // Which channel's token token will expire, if it is '', message service token will expire or stream service token will expire
    });

消息格式转换

MessageEvent 中的 message 字段为 Uint8List 类型,当你收到字符串类型的消息后,可以使用 dart:convert 库中的 utf8.decode() 方法将其转换成 String 类型:

Dart
// convert Uint8List to String. ! means forced conversion
String message = utf8.decode(event.message!);

删除事件监听

为避免内存泄漏、错误和异常(即空指针异常)引起的性能下降,声网建议你在不需要使用某个事件处理程序时对其进行注销。如需注销事件监听程序,则需在添加事件监听时避免采用匿名函数的方式,以下是添加和注销事件监听程序的示例代码。

Dart
// 定义消息时间处理函数
void onMessageReceived(MessageEvent event) {
  print('Received message event: $event');
}
// 注册 message event
rtmClient.addListener(
  message: onMessageReceived
);
//移除 message event
rtmClient.removeListener(
    message: onMessageReceived
);

事件通知类型

RTM 一共有 7 种类型事件,对应的有 7 种事件监听程序。你可以查看 API 参考的事件监听章节,了解每个事件监听程序传入参数的详细信息。

事件监听程序描述
message接收所有订阅的 Message Channel 中的消息通知或你加入的所有 Stream Channel 中订阅的 Topic 消息通知。事件负载数据中包含频道名称、频道类型、Topic 名称、事件发送者、消息负载数据类型等信息。
presence接收所有订阅的 Message Channel 或者你加入的所有 Stream Channel 中远端用户的在线状态事件通知。事件负载数据中包含频道名称、频道类型、事件类型、事件发送者、用户临时状态数据等信息。
topic接收加入的所有 Stream Channel 中 Topic 变更事件通知。事件负载数据中包含频道名称、事件类型、Topic 名称、事件发送者(即 Topic 详情)等信息。
storage接收订阅的 Message Channel 及加入的 Stream Channel 中所有的 Channel Metadata 事件通知,以及所有订阅用户的 User Metadata 事件通知。事件负载数据中包含频道名称、频道类型、事件类型(即具体 Metadata 数据)等信息。
lock接收订阅的 Message Channel 及加入的 Stream Channel 中所有的 Lock 事件通知。事件负载数据中包含有频道名称、频道类型、事件类型、锁详情等信息。
linkState接收客户端网络连接状态变更的事件通知,包含变更前后的连接状态、服务类型、导致变更的操作类型、变更原因、频道列表等信息。
token接收客户端 Token 将要过期的事件通知。
表格内容超出当前宽度,可横向滚动查看更多列。

完成事件监听处理程序后,你可以通过订阅频道或 Topic 来接收指定的 Message Channel 或 Stream Channel 中的消息和事件通知了。详见订阅 Message Channel 和订阅 Topic。