Flutter

Updated

API reference for the Agora Signaling Flutter SDK.

The Signaling SDK API reference is divided into the following sections:

Setup

The API reference for the Signaling SDK documents interface descriptions, methods, basic usage, and return values of the Signaling APIs.

RtmConfig

Description

Use the RtmConfig to set additional properties for Signaling initialization. These configuration properties will take effect throughout the lifecycle of the Signaling client and affect the behavior of the Signaling client.

Method

You can create RtmConfig instances as follows:

RtmConfig({
    int heartbeatInterval,
    int presenceTimeout,
    bool useStringUserId,
    bool ispPolicyEnabled,
    RtmProtocolType protocolType,
    RtmLogConfig logConfig,
    RtmProxyConfig proxyConfig,
    RtmEncryptionConfig encryptionConfig,
    RtmPrivateConfig privateConfig,
    Set<RtmAreaCode> areaCode
})
PropertiesTypeRequiredDefaultDescription
areaCodeRtmAreaCodeOptionalglobService area code, you can choose according to the region where your business is deployed. See RtmAreaCode.
protocolTypeRtmProtocolTypeOptionaltcpUdpProtocol types for message transmission. Signaling by default utilizes one-way TCP and one-way UDP protocols for transmission, but you have the flexibility to modify the protocol types based on your requirements. See RtmProtocolType.
presenceTimeoutintOptional300Presence timeout in seconds, and the value range is [5,300]. This parameter refers to the delay imposed by the Signaling server before sending a remoteTimeout event notification to other users once it determines that a client has timed out. If the client reconnects and returns to the channel within the specified time, the Signaling server does not send the remoteTimeout event notification to other participants or delete the temporary user data associated with the user.
heartbeatIntervalintOptional5Heartbeat interval in seconds, and the value range is [5,1800]. This parameter refers to the time interval at which the client sends heartbeat packets to the Signaling server. If the client fails to send heartbeat packets to the Signaling server within the specified time, the Signaling server determines that the client has timed out. Please note that this parameter affects the PCU count, which in turn affects billing.
useStringUserIdboolOptionaltrueWhether to use string-type user IDs:
- true: Use string-type user IDs.
- false: Use int-type user IDs. The SDK automatically converts string-type user IDs to int-type ones. In this case, the userId parameter must be a numeric string (for example, "123457"), otherwise initialization fails.When using Agora RTC and Signaling products at the same time, it is necessary to ensure that the userId parameter is consistent.
ispPolicyEnabledboolOptionalfalseWhether to enable the ISP policy. In IoT scenarios, devices may be restricted by the Internet Service Provider (ISP). Use this field to configure the SDK connection mode.
logConfigRtmLogConfigOptional-Log configuration properties such as the log storage size, storage path, and level.
proxyConfigRtmProxyConfigOptional-When using the Proxy feature of Signaling, you need to configure this parameter.
encryptionConfigRtmEncryptionConfigOptional-When using the client-side encryption feature of Signaling, you need to configure this parameter.
privateConfigRtmPrivateConfigOptional-When using the private deployment feature of Signaling, you need to configure this parameter.
RtmLogConfig
RtmLogConfig({
    String filePath,
    int fileSizeInKB,
    RtmLogLevel level
})

Use the RtmLogConfig instance to configure and store local log files named agora.log. During the debugging phase, you can greatly improve efficiency by storing and tracking the running status of the app through logs. If you encounter complex problems and need Agora technical support to assist with the investigation, you need to provide the log information. RtmLogConfig contains the following properties:

PropertiesTypeRequiredDefaultDescription
filePathStringOptional-Log file storage paths.
fileSizeInKBintOptional1024Log file size in KB, with a value range of [128,1024].
- If the value you enter is less than 128, the SDK sets the value to 128.
- If the value you enter is greater than 1024, the SDK sets the value to 1024.
levelRtmLogLevelOptionalinfoOutput level of log information. See RtmLogLevel.
RtmProxyConfig
RtmProxyConfig({
    RtmProxyType proxyType,
    String server,
    int port,
    String account,
    String password
})

Use the RtmProxyConfig instance to set properties related to the client Proxy service. In some restricted network environments, you might need to use this feature.

Caution

You need to keep your Proxy username and password safe. The Signaling SDK does not parse, store, or forward your username and password in any way. In addition, if you modify the Proxy settings during the app running process, the settings will take effect only after restarting the Signaling client.

RtmProxyConfig contains the following properties:

PropertiesTypeRequiredDefaultDescription
proxyTypeRtmProxyTypeOptionalnoneProxy protocol type. See RtmProxyType.
serverStringOptional-Proxy server domain name or IP address.
portintOptional0Proxy listening port.
accountStringOptional-Proxy login account.
passwordStringOptional-Proxy login password.
RtmEncryptionConfig
RtmEncryptionConfig({
    RtmEncryptionMode encryptionMode,
    String encryptionKey,
    Uint8List encryptionSalt
})

Use the RtmEncryptionConfig instance to set the properties required for the client-side encryption. After successfully setting encryption modes, encryption keys, and other related properties, the SDK automatically encrypts and decrypts all messages sent or all statuses set by the user on the client side.

Caution

Once you set the encryption feature, all users must use the same encryption mode and key, otherwise users cannot communicate with each other.

RtmEncryptionConfig contains the following properties:

PropertiesTypeRequiredDefaultDescription
encryptionModeRtmEncryptionModeOptionalnoneEncryption mode. See RtmEncryptionMode.
encryptionKeyStringOptional-User-defined encryption key, unlimited length. Agora recommends using a 32-byte key.
encryptionKdfSaltUint8ListOptionalnullUser-defined encryption salt, length is 32 bytes. Agora recommends using OpenSSL to generate salt on the server side.
RtmPrivateConfig
RtmPrivateConfig({
    Set<RtmServiceType> serviceType,
    List<String> accessPointHosts
})

Use the RtmPrivateConfig instance to set the properties required for the private deployment.

RtmPrivateConfig contains the following properties:

PropertiesTypeRequiredDefaultDescription
serviceTypeSet&lt;RtmServiceType&gt;Optional-Service type. See RtmServiceType.
accessPointHostsList&lt;String&gt;Optional-An array of server addresses, where you can fill in domain names or IP addresses.

Basic usage

final proxyConfig = RtmProxyConfig(
      protocolType : RtmProxyType.http,
      server : "x.x.x.x",
      port : 8080,
      account : "Tony",
      password : "pwd" );

final logConfig = RtmLogConfig(
      filePath : "xxxx",
      fileSizeInKB : 1024;
      leave : RtmLogLevel.info );

final encryptionConfig = RtmEncryptionConfig(
      encryptionMode : RtmEncryptionMode.aes256Gcm,
      encryptionKey : "XXXXX",
      encryptionSalt : [1,2,3,4,5]);

final rtmConfig = RtmConfig(
      heartbeatInterval : 10,
      presenceTimeout : 5,
      proxyConfig : proxyConfig,
      logConfig : logConfig,
      areaCode : `RtmAreaCode.cn, RtmAreaCode.na`,
      encryptionConfig : encryptionConfig );

Initialization

Description

Call the RTM() method to create and initialize the Signaling Client instance.

Information


- You need to create and initialize a client instance before calling other Signaling APIs.
- To distinguish each user or device, you need to ensure that the userId parameter is globally unique and remains unchanged throughout the user or device's lifecycle.

Method

You can create and initialize an instance as follows:

Future<(RtmStatus,RtmClient)> RTM(
    String appId,
    String userId,
    {
        RtmConfig rtmConfig
    }
)
ParametersTypeRequiredDefaultDescription
appIdStringRequired-App ID obtained when creating a project in the Agora Console.
userIdStringRequired-User ID for identifying a user or a device. To distinguish each user or device, you need to ensure that the userId parameter is globally unique and remains unchanged throughout the user or device's lifecycle.
rtmConfigRtmConfigOptional-Initialize the configuration parameters of the Signaling Client. See RtmConfig.

Basic usage

final proxyConfig = RtmProxyConfig(
      protocolType : RtmProxyType.http,
      server : "x.x.x.x",
      port : 8080,
      account : "Tony",
      password : "pwd" );

final logConfig = RtmLogConfig(
      filePath : "xxxx",
      fileSizeInKB : 1024,
      leave : RtmLogLevel.info );

final encryptionConfig = RtmEncryptionConfig(
      encryptionMode : RtmEncryptionMode.aes256gcm,
      encryptionKey : "XXXXX",
      encryptionSalt : [1,2,3,4,5]);

final rtmConfig = RtmConfig(
      heartbeatInterval : 10,
      presenceTimeout : 5,
      proxyConfig : proxyConfig,
      logConfig : logConfig,
      areaCode : `RtmAreaCode.cn, RtmAreaCode.na`,
      encryptionConfig : encryptionConfig );

var (status,rtmClient) = await RTM("myAppId", "Tony", rtmConfig:rtmConfig);
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus,RtmClient)&gt; tuple. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a Signaling client instance for subsequent calls to other Signaling APIs.

Event Listeners

Description

Signaling has a total of 7 types of event notifications, as shown in the following table:

Event TypeDescription
messageReceive message event notifications in subscribed message channels and subscribed topics.
presenceReceive presence event notifications in subscribed message channels and joined stream channels.
topicReceive all topic event notifications in joined stream channels.
storageReceive channel metadata event notifications in subscribed message channels and joined stream channels, and the user metadata event notification of the subscribed users.
lockReceive lock event notifications in subscribed message channels and joined stream channels.
linkStateReceive event notifications when client connection status changes. For details, see LinkStateEvent.
tokenReceive event notifications when the client tokens are about to expire.

Add event listeners

You can add an event listener object as follows:

rtmClient.addListener({
    Function(MessageEvent event)? message = null,
    Function(PresenceEvent event)? presence = null,
    Function(TopicEvent event)? topic = null,
    Function(StorageEvent event)? storage = null,
    Function(LockEvent event)? lock = null,
    Function(LinkStateEvent event)? linkState = null,
    Function(TokenEvent event)? token = null,
})

Remove event listeners

You can remove an event listener object as follows:

rtmClient.removeListener({
    Function(MessageEvent event) message = null,
})
MessageEvent

Message event.

MessageEvent contains the following properties:

PropertiesTypeDescription
channelTypeRtmChannelTypeChannel types. See RtmChannelType.
messageTypeRtmMessageTypeMessage type. See RtmMessageType.
channelNameStringChannel name.
channelTopicStringTopic name.
messageUint8ListMessage.
messageLengthintMessage length.
publisherStringUser ID of the message publisher.
customTypeStringA user-defined field. Only supports string type.
timestampintThe timestamp when the event occurs.
PresenceEvent

User presence event.

PresenceEvent contains the following properties:

PropertiesTypeDescription
typeRtmPresenceEventTypePresence event type. See RtmPresenceEventType.
channelTypeRtmChannelTypeChannel types. See RtmChannelType.
channelNameStringChannel name.
publisherStringUser ID of the message publisher.
stateItemsList&lt;StateItem&gt;Key-value pair that identifies the user's presence state.
intervalIntervalInfoIn the Interval state, the aggregated incremental information of event notifications such as user joining, leaving, timeout, and status change in the previous period of the current channel.
snapshotSnapshotInfoWhen the user first joins the channel, the server pushes the snapshot data of all users in the current channel and their statuses to the user.
timestampintThe timestamp when the event occurs.

StateItem data type contains the following properties:

PropertiesTypeDescription
keyStringKey of the user state. If the specified key already exists, the SDK overwrites the value; if the specified key does not exist, the SDK creates the key-value pair.
valueStringValue of the user state.

IntervalInfo contains the following properties:

PropertiesTypeDescription
joinUserListUserListList of users who joined the channel in the previous cycle.
leaveUserListUserListList of users who left the channel in the previous cycle.
timeoutUserListUserListList of users who timed out joining the channel in the previous cycle.
userStateListList&lt;UserState&gt;List of users whose status has changed in the previous cycle. Contains user ID and status key-value pairs.

SnapshotInfo contains the following properties:

PropertiesTypeDescription
userStateListList&lt;UserState&gt;Snapshot information of the user when first joining the channel, including user ID and key-value pairs of status.

UserList contains the following properties:

PropertiesTypeDescription
usersList&lt;String&gt;User list.

UserState contains the following properties:

PropertiesTypeDescription
userIdStringUser ID.
statesList&lt;StateItem&gt;List of online users and their temporary state information in a specified channel.
TopicEvent

Topic event.

TopicEvent contains the following properties:

PropertiesTypeDescription
typeRtmTopicEventTypeTopic event type. See RtmTopicEventType.
channelNameStringChannel name.
publisherStringUser ID.
topicInfosList&lt;TopicInfo&gt;Topic information.
timestampintThe timestamp when the event occurs.

TopicInfo data type contains the following properties:

PropertiesTypeDescription
topicStringTopic name.
publishersList&lt;PublisherInfo&gt;Message publisher array.

PublisherInfo data type contains the following properties:

PropertiesTypeDescription
publisherUserIdStringUser ID of the message publisher.
publisherMetaStringMetadata of the message publisher.
StorageEvent

Storage event.

StorageEvent contains the following properties:

PropertiesTypeDescription
channelTypeRtmChannelTypeChannel types. See RtmChannelType.
storageTypeRtmStorageTypeStorage type. See RtmStorageType.
eventTypeRtmStorageEventTypeStorage event type. See RtmStorageEventType.
targetStringUser ID or channel name.
data*Metadata item. See ``.
timestampintThe timestamp when the event occurs.
LockEvent

Lock event.

LockEvent contains the following properties:

PropertiesTypeDescription
channelTypeRtmChannelTypeChannel types. See RtmChannelType.
eventTypeRtmLockEventTypeLock event type. See RtmLockEventType.
channelNameStringChannel name.
lockDetailListList&lt;LockDetail&gt;Details of lock.
countintLock count.
timestampintThe timestamp when the event occurs.

The LockDetail data type contains the following properties:

PropertiesTypeDescription
lockNameStringLock name.
ownerStringThe ID of the user who has a lock.
ttlintThe expiration time of the lock. The value is in seconds, ranging from [10 to 300]. When the user who owns the lock goes offline, if the user returns to the channel within the time they can still use the lock; otherwise, the lock is released and the users who listen for the lock event receives the lockReleased event.
LinkStateEvent

SDK link state event.

LinkStateEvent data type contains the following properties:

ParametersTypeDescription
currentStateRtmLinkStateThe current link state. See RtmLinkState.
previousStateRtmLinkStateThe previous link state. See RtmLinkState.
serviceTypeRtmServiceTypeThe network connection type. See RtmServiceType.
operationRtmLinkOperationThe operation that triggered the current state transition. See RtmLinkOperation.
reasonStringThe reason of the current state transition. See RtmLinkStateChangeReason.
affectedChannelsList&lt;String&gt;The channels affected by the current state transition.
unrestoredChannelsList&lt;String&gt;The information about the channels to which subscription or joining has not been restored, including the channel name, channel type, and temporary state data in the channel. Typically, this information is empty.
isResumedboolWithin 2 minutes of the disconnection, whether the state transitions from disconnected to connected. true refers to the state has transitioned.
timestampintThe timestamp when the event occurs.

RtmClient Signaling client instance.

login

Description

After creating and initializing the Signaling instance, you need to perform the login operation to log in to the Signaling service. After successful login, the client establishes a long connection with the Signaling server, and then the SDK allows the client to access Signaling resources.

Information

After the user successfully logs in to the Signaling service, the PCU of the application increases, which affects your billing data.

Method

You can log in to the Signaling system as follows:

Future<(RtmStatus, LoginResult?)> login(String token);
ParametersTypeRequiredDefaultDescription
tokenStringRequired-The token used for logging into the Signaling system.
- If your project enables token authentication, you can provide either the Signaling temporary token or the Signaling token generated by your token server. See User authentication and Deploy Signaling token generator.
- If your project does not enable token authentication, you can enter an empty string or the App ID of a project that enables Signaling services.

Basic usage

var (status,response) = await rtmClient.login('your_token');
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, LoginResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a LoginResult type data, which currently does not contain any fields.

logout

Description

When you no longer need to operate, you can log out of the system. This operation affects the PCU item in your billing data.

Method

You can log out as follows:

Future<(RtmStatus, LogoutResult?)> logout();

Basic usage

var (status,response) = await rtmClient.logout();
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, LogoutResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a LogoutResult type data, which currently does not contain any fields.

releaseLock

Description

Once you no longer need the Signaling service, it is best to destroy the RtmClient instance. Doing so protects you from the performance degradation caused by memory leaks, errors, and exceptions.

Method

You can destroy the RtmClient instance as follows:

Future<RtmStatus> release();

Basic usage

var status = await rtmClient.release();

Return value

Regardless of whether you call this method successfully, this method returns an RtmStatus type data, with the following field definitions:

class RtmStatus {
    bool error; // Whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The API for this operation.
    String reason; // A brief description of the error reason for this operation.
}

You can refer to the errorCode field in the Error Codes to understand the cause of the error and find the corresponding solution.

User authentication

Authentication is the process of validating the identity of each user before they access a system. Agora uses digital tokens to authenticate users and their privileges.

Based on different transmission connections, the RTM SDK provides two types of services: MESSAGE service and STREAM service. These two services use different tokens and the methods for updating tokens are also different:

  • MESSAGE service: Use the renewToken() method under the rtmClient instance to update the token, providing authentication services for features such as Message Channel, User Channel, Presence, Storage, and Lock.
  • STREAM service: Use the renewToken() method under the streamChannel instance to update the token, providing authentication services for features such as Stream Channel and Topic.

Both services will return a token expiration notification in the token event. You can implement the business logic for automatic token renewal by listening to this event. The token is valid for up to 24 hours. Agora recommends that you update the token before it expires. This article describes how to update the token.

For more information on generating and using tokens, see Secure authentication with tokens.

renewToken

Description

To ensure timely token updates, Agora recommends listening for the token callback. See Event listeners for details. Once you successfully add the event listener, when the token is about to expire within 30 seconds, the SDK triggers the token callback to notify the user about the impending token expiration.

  • Call rtmClient.renewToken(String token) to renew the token for MESSAGE service.
  • Call streamChannel.renewToken(String token) to renew the token for STREAM service.

Method

You can call the renewToken method as follows:

Future<(RtmStatus, RenewTokenResult?)> renewToken(String token);
ParametersTypeRequiredDefaultDescription
tokenStringRequired-Fill in the corresponding token in this parameter according to the type of service you use.
- For the MESSAGE service, fill in a newly generated RTM token.
- For the STREAM service, fill in a newly generated RTC token.

Basic Usage

class TokenResult {
    final String status;
    final String token;
    TokenResult(this.status, this.token);
}

 // Define the function to fetch token
Future<TokenResult> fetchToken({required String channelName}) async {
 // Request token from the token provider
    ......
    String status = "success";
    String token = "your_token_here";
    return TokenResult(status, token);
}

rtmClient.addListener({
    token:(event) => {
        if(event.channelName == '') { // When the channelName in the event is empty, it means the MESSAGE service token is about to expire
            var result = await fetchToken(); // Fetch the MESSAGE service token
            rtmClient.renewToken(result.token); // Renew the MESSAGE service token
        } else { // When the channelName in the event is not empty, it means the STREAM service token is about to expire
            var result = await fetchToken(channelName: event.channelName); // Fetch the STREAM service token
            streamChannel.renewToken(result.token); // Renew the STREAM service token
        }
    }
});

Return Value

Calling this method returns a tuple of type Future&lt;(RtmStatus, RenewTokenResult?)&gt;. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call is successful, the second item in the tuple returns data of type RenewTokenResult, defined as follows:
  class RenewTokenResult {
      final RtmServiceType serverType; // Service type
      final String channelName; // Channel name
  }

Channels

Signaling provides a highly efficient channel management mechanism for data transmission. Any user who subscribes or joins a channel can receive messages and events transmitted within 100 milliseconds. Signaling allows clients to subscribe to hundreds or even thousands of channels. Most Signaling APIs perform actions such as sending, receiving, and encrypting based on channels.

Based on capabilities of Agora, Signaling channels are divided into three types to match different application use-cases:

  • Message Channel: Follows the industry-standard Pub/Sub (publish/subscribe) mode. You can send and receive messages within the channel by subscribing to a channel, and do not need to create the channel in advance. There is no limit to the number of publishers and subscribers in a channel.
  • User Channel: Based on the Pub/Sub (publish/subscribe) mode for point-to-point messaging. Users can directly send messages to a specified user without subscribing to a channel. To receive messages, users only need to listen to the message event.
  • Stream Channel: Follows a concept similar to the observer pattern in the industry, where users need to create and join a channel before sending and receiving messages. You can create different topics in the channel, and messages are organized and managed through topics.

RtmClient Signaling client instance

subscribeTopic

Description

Signaling provides event notification capabilities for messages and states. By listening for callbacks, you can receive messages and events within subscribed channels. For information on how to add and set event listeners, see Event Listeners.

By calling the subscribeTopic method, the client can subscribe to a message channel and start receiving messages and event notifications within the channel. After successfully calling this method, users who subscribe to the channel and enable the presence event listener can receive a remoteJoinChannel type of the presence event. See Event Listeners.

Information

This method only applies to message channels.

Method

You can call the subscribeTopic method as follows:

Future<(RtmStatus, SubscribeResult?)> subscribe(
    String channelName,
    {
        bool withMessage = true,
        bool withMetadata = false,
        bool withPresence = true,
        bool withLock = false,
        bool beQuiet = false
    }
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
withMessageboolOptionaltrueWhether to subscribe to message event notifications in the channel.
withPresenceboolOptionaltrueWhether to subscribe to presence event notifications in the channel.
withMetadataboolOptionalfalseWhether to subscribe to storage event notifications in the channel.
withLockboolOptionalfalseWhether to subscribe to lock event notifications in the channel.
beQuietboolOptionalfalseWhether to set the silent mode. If you set this parameter as true, the SDK has the following behaviors:
- You can still receive other users' event notifications.
- Event notifications related to your channel activity such as subscribing or unsubscribing the channel, and actions related to setting, getting, or deleting temporary user states, can not be broadcasted to other users.
- When calling the getOnlineUsers method, your information can not be found.
- When calling the getUserChannels method, channels that you subscribe in silent mode can not be detected.

Basic usage

var (status,response) = await rtmClient.subscribe("myChannel", withPresence:true, beQuiet:true);
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, SubscribeResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a SubscribeResult type data, defined as follows:
  class SubscribeResult {
      final String channelName; // The channel of the current operation
  }

unsubscribeTopic

Description

If you no longer need to subscribe to a channel, you can call the unsubscribeTopic method to unsubscribe from the channel. After successfully calling this method, users who subscribe to the channel and enable event listeners can receive the remoteLeaveChannel type of the presence event notification. See Event Listeners.

Information

This method only applies to message channels.

Method

You can call the unsubscribeTopic method as follows:

Future<(RtmStatus, UnsubscribeResult?)> unsubscribe(String channelName);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.

Basic usage

var (status,response) = await rtmClient.unsubscribe("myChannel");
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, UnsubscribeResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple will return a UnsubscribeResult type data, defined as follows:
  class UnsubscribeResult {
      final String channelName; // The channel of the current operation
  }

createAgoraRtmClient

Description

Before using a stream channel, you need to call the createAgoraRtmClient method to create a StreamChannel instance. After successfully creating the instance, you can call its relevant methods to implement functions, such as joining the channel, leaving the channel, sending messages in a topic, and subscribing to messages in a topic.

Information

This method only applies to stream channels.

Method

You can call the createAgoraRtmClient method as follows:

Future<(RtmStatus, StreamChannel?)> createStreamChannel(String channelName);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.

Basic usage

var (status, stChannel) = await rtmClient.createStreamChannel("myStChannel");
if (status.error == true) {
    print(status);
} else {
    print("create Stream Channel Success!");
}

Return value

Calling this method returns a Future&lt;(RtmStatus, StreamChannel?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple will return a StreamChannel instance object, which can be used to call related API of StreamChannel.

StreamChannel Stream channel instance

joinTopic

Description

After successfully creating a stream channel, you can call the joinTopic method to join the stream channel.

Once you join the channel, you can implement channel-related functions. At this point, users who subscribe to the channel and add event listeners can receive the following event notifications:

  • For the local user:
    • The snapshot type of the presence event.
    • The snapshot type of the topic event.
  • For remote users: The remoteJoinChannel type of the presence event.

Information

This method only applies to stream channels.

Method

You can call the joinTopic method as follows:

Future<(RtmStatus, JoinResult?)> join({
    String? token,
    bool withMetadata = false,
    bool withPresence = true,
    bool withLock = false,
    bool beQuiet = false
    }
);
ParametersTypeRequiredDefaultDescription
tokenStringOptional-The token used for joining a stream channel.
- If your project enables token authentication, you can provide either the RTC temporary token or the RTC token generated by your token server.
- If your project does not enable token authentication, you can enter an empty string or the App ID of a project that enables RTC and Signaling services.
withPresenceboolOptionaltrueWhether to subscribe to presence event notifications in the channel.
withMetadataboolOptionalfalseWhether to subscribe to storage event notifications in the channel.
withLockboolOptionalfalseWhether to subscribe to lock event notifications in the channel.
beQuietboolOptionalfalseWhether to set the silent mode. If you set this parameter as true, the SDK has the following behaviors:
- You can still receive other users' event notifications.
- Event notifications related to your channel activity such as joining or leaving the channel, and actions related to setting, getting, or deleting temporary user states, can not be broadcasted to other users.
- When calling the getOnlineUsers method, your information can not be found.
- When calling the getUserChannels method, channels that you subscribe in silent mode can not be detected.

Basic usage

var (status,response) = await stChannel.join(token:"myToken", withPresence:true);
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, JoinResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple will return a JoinResult type data, defined as follows:
  class JoinResult {
      final String channelName; // The channel of the current operation
      final String userId; // The user ID of the current operation
  }

leaveTopic

Description

If you no longer need to stay in a channel, you can call the leaveTopic method to leave the channel. After leaving the channel, you can no longer receive any messages, states, or event notifications from this channel. At the same time, you can no loger be the topic publisher or subscriber of all topics. If you want to restore your previous publisher role and subscribing relationship, you need to call joinTopic, joinTopic and subscribeTopic methods in order.

After successfully leaving the channel, remote users in the channel can receive the remoteLeaveChannel type of the presence event notification. For details, see Event Listeners.

Information

This method only applies to stream channels.

Method

You can call the leaveTopic method as follows:

Future<(RtmStatus, LeaveResult?)> leave();

Basic usage

var (status,response) = await stChannel.leave();
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, LeaveResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple will return a LeaveResult type data, defined as follows:
  class LeaveResult {
      final String channelName; // The channel of the current operation
      final String userId; // The user ID of the current operation
  }

releaseLock

Description

If you no longer need a channel, you can call the releaseLock method to destroy the corresponding stream channel instance and release resources. Calling the releaseLock method does not destroy the stream channel, and it can be re-joined later by calling createAgoraRtmClient and joinTopic again.

Information

This method only applies to stream channels. If you don't call leaveTopic to leave the channel before directly calling releaseLock to destroy the stream channel instance, the SDK automatically calls the leaveTopic and triggers the corresponding event.

Method

You can call the releaseLock method as follows:

Future<RtmStatus> release();

Basic usage

var status = await stChannel.release();
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Regardless of whether you call this method successfully, this method returns an RtmStatus type data, with the following field definitions:

class RtmStatus {
    bool error; // Whether there is an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The API of this operation.
    String reason; // A brief description of the reason for the error in this operation.
}

You can refer to the errorCode field in the Error Codes to understand the cause of the error and find the corresponding solution.

Topics

Topic is a data stream management mechanism in stream channels. Users can use topics to subscribe to and distribute data streams, as well as notify events in data streams in stream channels.

Information

Topics only exist in stream channels. Therefore, before using relevant features, you need to create the StreamChannel instance.

StreamChannel Stream channel instance

joinTopic

Description

The purpose of joining a topic is to register as one of the message publishers for the topic, so that the user can send messages in the topic. This operation does not affect whether or not the user becomes a subscriber to the topic.

Information

  • Currently, Signaling supports a single client joining up to 8 topics in the same stream channel at a time.
  • Before joining a topic, a user needs to create a StreamChannel instance and call the joinTopic method to join the channel.

After successfully joining a topic, users who subscribe to that topic and add event listeners can receive the remoteJoinTopic type of the topic event notification. For details, see Event Listeners.

Method

You can call the joinTopic method as follows:

Future<(RtmStatus, JoinTopicResult?)> joinTopic(
    String topic,
    {
        RtmMessageQos qos = RtmMessageQos.unordered,
        RtmMessagePriority priority = RtmMessagePriority.normal,
        String? meta = '',
        bool? syncWithMedia = false
    }
);
ParametersTypeRequiredDefaultDescription
topicStringRequired-Topic name.
qosRtmMessageQosOptionalunorderedWhether the data transmitted in the topic is ordered. See RtmMessageQos.
priorityRtmMessagePriorityOptionalnormalThe priority of data transmission in the topic compared to other topics in the same channel. See RtmMessagePriority.
metaStringOptional-Adds additional metadata when joining the topic.
syncWithMediaboolOptionalfalseWhether the data sent in this topic is synchronized (timestamp-aligned) with the RTC audio and video data stream of the common channel.

Basic usage

var (status,response) = await stChannel.joinTopic("myTopic");

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, JoinTopicResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a JoinTopicResult object, defined as follows:
  class JoinTopicResult {
      final String channelName; // Channel name
      final String userId; // Current userId
      final String topic; // Topic name
      final String meta; // Additional metadata
  }

publishTextMessage

Description

Use the publishTextMessage method to send string messages to a topic. Users who have subscribed to the topic and the message publisher in the channel can receive the message within 100 milliseconds. Before calling the publishTextMessage method, users need to join the stream channel, and then register as a message publisher for that topic by calling the joinTopic method.

The messages sent by users are encrypted with TLS during transmission, and data link encryption is enabled by default and cannot be disabled. To achieve a higher level of data security, users can also enable client encryption during initialization. For details, see Setup.

Method

You can call the publishTextMessage method as follows:

Future<(RtmStatus, PublishTopicMessageResult?)> publishTextMessage(
    String topic,
    String message,
    {
        int sendTs = 0,
        String? customType
    }
);
ParametersTypeRequiredDefaultDescription
topicStringRequired-Topic name.
messageStringRequired-Message payload.
sendTsintOptional0The timestamp when the SDK sends a message. This parameter is only valid when you set syncWithMedia = true in the joinTopic method. The SDK synchronizes data with RTC audio and video streams based on this timestamp.
customTypeStringOptional-A user-defined field. Only supports string type.

Basic usage

var message = {
    type: "poll",
    question: "Which option is right?",
    answers: {
        A: "Apple",
        B: "Banana",
        C: "Blackberry"
    },
    sender: "Max"
}

var payload = json.encode(message);
var (status,response) =
    await stChannel.publishTextMessage("myTopic", payload, customType:"poll");
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, PublishTopicMessageResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a PublishTopicMessageResult object, defined as follows:
  class PublishTopicMessageResult {
      final String channelName; // Channel name
      final String topic; // Topic name
  }

publishBinaryMessage

Description

Use the publishBinaryMessage method to send binary messages to a topic. Users who have subscribed to the topic and the message publisher in the channel can receive the message within 100 milliseconds. Before calling the publishBinaryMessage method, users need to join the stream channel, and then register as a message publisher for that topic by calling the joinTopic method.

The messages sent by users are encrypted with TLS during transmission, and data link encryption is enabled by default and cannot be disabled. To achieve a higher level of data security, users can also enable client encryption during initialization. For details, see Setup.

Method

You can call the publishBinaryMessage method as follows:

Future<(RtmStatus, PublishTopicMessageResult?)> publishBinaryMessage(
    String topic,
    Uint8List message,
    {
        int sendTs = 0,
        String? customType
    }
);
ParametersTypeRequiredDefaultDescription
topicStringRequired-Topic name.
messageUint8ListRequired-Message payload.
sendTsintOptional0The timestamp when the SDK sends a message. This parameter is only valid when you set syncWithMedia = true in the joinTopic method. The SDK synchronizes data with RTC audio and video streams based on this timestamp.
customTypeStringOptional-A user-defined field. Only supports string type.

Basic usage

var payload = [1,2,3,4];
var (status,response) = await stChannel.publishBinaryMessage(
      "myTopic",
      payload,
      customType:"UINT8LIST"
    );
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, PublishTopicMessageResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a PublishTopicMessageResult object, defined as follows:
  class PublishTopicMessageResult {
      final String channelName; // Channel name
      final String topic; // Topic name
  }

leaveTopic

Description

When you no longer need to publish messages to a topic, to release resources, you can call the leaveTopic method to unregister as a message publisher for that topic. This method does not affect whether or not you subscribe to that topic or any other operations performed by other users on that topic.

After successfully calling this method, users who subscribe to the channel and enable event listeners can receive the remoteLeaveTopic type of the topic event notification. See Event Listeners.

Method

You can call the leaveTopic method as follows:

Future<(RtmStatus, LeaveTopicResult?)> leaveTopic(String topic);
ParametersTypeRequiredDefaultDescription
topicStringRequired-Topic name.

Basic usage

var (status,response) = await stChannel.leaveTopic("myTopic");

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, LeaveTopicResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a LeaveTopicResult object, defined as follows:
  class LeaveTopicResult {
      final String channelName; // Channel name
      final String userId; // User ID
      final String topic; // Topic name
      final String meta; // Additional metadata
  }

subscribeTopic

Description

After joining the channel, you can call the subscribeTopic method to subscribe to the message publisher of the topic in the channel.

subscribeTopic is an incremental method. For example, if you call this method for the first time with a subscribing list of [UserA, UserB], and then call it again with a subscribing list of [UserB, UserC], the final successful subscribing result is [UserA, UserB, UserC].

A user can subscribe to a maximum of 50 topics in each channel, and a maximum of 64 message publishers in each topic. See API usage restrictions.

Method

You can call the subscribeTopic method as follows:

Future<(RtmStatus, SubscribeTopicResult?)> subscribeTopic(
    String topic,
    {
        List<String> users = const []
    }
);
ParametersTypeRequiredDefaultDescription
topicStringRequired-Topic name.
usersList&lt;String&gt;Optional-A list of UserId of message publishers that you want to subscribe to. If you do not set this property, you can randomly subscribe to up to 64 users by default.

Basic usage

Example 1: Subscribe to the specified message publisher in the topic.

var userList = ["Tony","Lily"];
var (status,response) = await stChannel.subscribeTopic("myTopic", users:userList);
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Example 2: Randomly subscribe to 64 message publishers in the topic.

var (status,response) = await stChannel.subscribeTopic("myTopic");
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, SubscribeTopicResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a SubscribeTopicResult object, defined as follows:
  class SubscribeTopicResult {
      final String channelName; // Channel name
      required this.userId; // User ID
      final String topic; // Topic name
      final List<String> succeedUsers; // List of successfully subscribed users
      final List<String> failedUsers; // List of users that failed to subscribe
  }

unsubscribeTopic

Description

If you are no longer interested in a specified topic, or no longer need to subscribe to one or more message publishers in the topic, you can call the unsubscribeTopic method to unsubscribe from the topic or the specified message publishers in the topic.

Method

You can call the unsubscribeTopic method as follows:

Future<(RtmStatus, UnsubscribeTopicResult?)> unsubscribeTopic(
    String topic,
    {
        List<String> users = const []
    }
);
ParametersTypeRequiredDefaultDescription
topicStringRequired-Topic name.
usersList&lt;String&gt;Optional-A list of UserId of message publishers that you want to unsubscribe from. If you do not set this property, you can randomly unsubscribe from up to 64 users.

Basic usage

Example 1: Unsubscribe the specified message publisher in the topic

var userList = ["Tony","Lily"];
var (status,response) = await stChannel.unsubscribeTopic("myTopic", users:userList);
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Example 2: Unsubscribe from all message publishers in the topic

var (status,response) = await stChannel.unsubscribeTopic("myTopic");
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, UnsubscribeTopicResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a UnsubscribeTopicResult object, defined as follows:
  class UnsubscribeTopicResult {
      final String channelName; // Channel name
      final String topic; // Topic name
  }

getSubscribedUserList

Description

If you need to get the list of publishers that you subscribe to in a specific topic, you can call the getSubscribedUserList method.

Method

You can call the getSubscribedUserList method as follows:

Future<(RtmStatus, GetSubscribedUserListResult?)> getSubscribedUserList(String topic);
ParametersTypeRequiredDefaultDescription
topicStringRequired-Topic name.

Basic usage

var (status,response) = await stChannel.getSubscribedUserList("myTopic");
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return value

Calling this method returns a Future&lt;(RtmStatus, GetSubscribedUserListResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a GetSubscribedUserListResult object, defined as follows:
  class GetSubscribedUserListResult {
      final String channelName; // Channel name
      final String topic; // Topic name
      final UserList users; // List of successfully subscribed users
  }

Messages

Sending and receiving messages is the most basic function of the Signaling service. Any message sent by the Signaling server can be delivered to any online subscribing user within 100 ms. Depending on your business requirements, you can send messages to one user only or broadcast messages to multiple users.

Signaling offers 3 types of channels: message channels, user channels, and stream channels. These channel types have the following differences in how messages are transmitted and methods are called:

  • Message Channel: The real-time channel. Messages are transmitted through the channel, and the channel is highly scalable. Local users can call the publishTextMessage method, set the channelType parameter to message, and set the channelName parameter to the channel name to send messages in the channel. The remote users can call the subscribeTopic method to subscribe to the channel and receive messages.
  • User Channel: The real-time channel. Messages are transmitted to the specified user. Local users can call the publishTextMessage method, set the channelType parameter to user, and set the channelName parameter to the user ID to send messages to the specified user. The specified remote users receive messages through the message event notifications.
  • Stream Channel: The streaming transmission channel. Messages are transmitted through the topic. Users need to join a channel first, and then join a topic. Local users can call the publishTextMessage method to send messages in the topic, and remote users can call the subscribeTopic method to subscribe to the topic and receive messages.

This page introduces how to send and receive messages in a message channel or a user channel.

RtmClient Signaling client instance

publishTextMessage

Description

You can directly call the publishTextMessage method to send string messages to all online users subscribed to this channel. Even if you do not subscribe to the channel, you can still send messages in the channel.

Information

The following practices can effectively improve the reliability of message transmission:
- The message payload should be within 32 KB; otherwise, the sending will fail.
- The upper limit of the rate at which messages are sent to a single channel is 60 QPS. If the sending rate exceeds the limit, some messages will be discarded. A lower rate is better, as long as the requirements are met.

After successfully calling this method, the SDK triggers a message event notification. Users who subscribe to the channel and enabled the event listener can receive this event notification. For details, see Event Listeners.

Method

You can call the publishTextMessage method as follows:

Future<(RtmStatus, PublishResult?)> publish(
    String channelName,
    String message,
    {
        RtmChannelType channelType = RtmChannelType.message,
        String? customType
    }
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Fill in a channel name to send messages in a specified channel, or fill in a user ID to send messages to a specified user.
messageStringRequired-Message payload.
channelTypeRtmChannelTypeOptionalmessageChannel type. See RtmChannelType.
customTypeStringOptional-A user-defined field. Only supports string type.

Basic usage

Example 1: Send string messages to a specified message channel.

var message = {
    type: "poll",
    question: "Which option is right?",
    answers: {
        A: "Apple",
        B: "Banana",
        C: "Blackberry"
    },
    sender: "Max"
}

var payload = json.encode(message);
var (status,response) =
    await rtmClient.publish("myChannel", payload, channelType:RtmChannelType.message, customType:"poll");
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Example 2: Send string messages to a specified user channel.

var message = {
    type: "chatInvite",
    channel: "this is the channel you are being invited to",
    message: "Hi Tony, welcome to the team!"
}

var payload = json.encode(message);
var (status,response) =
    await rtmClient.publish("userId", payload, channelType:RtmChannelType.user, customType:"chatInvite");
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return Values

Calling this method returns a Future&lt;(RtmStatus, PublishResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a PublishResult type, which currently does not contain any fields.

publishBinaryMessage

Description

You can directly call the publishBinaryMessage method to send binary messages to all online users subscribed to this channel. Even if you do not subscribe to the channel, you can still send messages in the channel.

Information

The following practices can effectively improve the reliability of message transmission:
- The message payload should be within 32 KB; otherwise, the sending will fail.
- The upper limit of the rate at which messages are sent to a single channel is 60 QPS. If the sending rate exceeds the limit, some messages will be discarded. A lower rate is better, as long as the requirements are met.

After successfully calling this method, the SDK triggers a message event notification. Users who subscribe to the channel and enabled the event listener can receive this event notification. For details, see Event Listeners.

Method

You can call the publishBinaryMessage method as follows:

Future<PublishResult> publishBinaryMessage(
    String channelName,
    Uint8List message,
    {
        RtmChannelType channelType = RtmChannelType.message,
        String? customType
    }
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Fill in a channel name to send messages in a specified channel, or fill in a user ID to send messages to a specified user.
messageUint8ListRequired-Message payload.
channelTypeRtmChannelTypeOptionalmessageChannel type. See RtmChannelType.
customTypeStringOptional-A user-defined field. Only supports string type.

Basic usage

Example 1: Send binary messages to a specified message channel.

var payload = [1,2,3,4];
var (status,response) = await rtmClient.publishBinaryMessage(
      "myChannel",
      payload,
      channelType:RtmChannelType.message,
      customType:"UINT8LIST"
    );
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Example 2: Send binary messages to a specified user channel.

var payload = [1,2,3,4];
var (status,response) = await rtmClient.publishBinaryMessage(
      "myChannel",
      payload,
      channelType:RtmChannelType.message,
      customType:"UINT8LIST"
    );
if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return Values

Calling this method returns a Future&lt;(RtmStatus, PublishResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a PublishResult type, which currently does not contain any fields.

Receive

Signaling provides event notifications for messages, states, and event changes. By listening for callbacks, you can receive messages and events within subscribed channels. The example code below shows how to receive messages from the user channel:

rtm.addListener(
    message: (event) {
        print('Received a message from $`event.channelName`');
        print('Message Type is $`event.messageType`');
        print('Message : $`event.message`');
      }
    );

Message Format Conversion

The message field in MessageEvent is of type Uint8List. When you receive a string message, you can convert it to String type using the utf8.decode() method from the dart:convert library:

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

For information on how to add and set event listeners, see Event Listeners.

Presence

The presence feature provides the ability to monitor user online, offline, and user historical state change. With the Presence feature, you can get real-time access to the following information:

  • Real-time event notification when a user joins or leaves a specified channel.
  • Real-time event notification when the custom temporary user state changes.
  • Query which channels a specified user has joined or subscribed to.
  • Query which users have joined a specified channel and their temporary user state data.

Information

Presence applies to both message channels and stream channels.

RtmPresence Presence instance

getOnlineUsers

Description

By calling the getOnlineUsers method, you can query real-time information about the number of online users, the list of online users, and the temporary state of online users in a specified channel.

Method

You can call the getOnlineUsers method as follows:

Future<(RtmStatus, WhoNowResult?) whoNow(
    String channelName,
    RtmChannelType channelType,
    {
        bool includeUserId = true,
        bool includeState = false,
        String? page = ''
    }
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
includeUserIdboolOptionaltrueWhether the returned result includes the user ID of online members.
includeStateboolOptionalfalseWhether the returned result includes temporary state data of online users.
pageStringOptional-Page number of the returned result. If you do not provide this property, the SDK returns the first page by default. You can check whether there is next page in the returned result.

Basic usage

var (status, response) = await rtmClient.getPresence.getOnlineUsers(
    "myChannel",
    RtmChannelType.message,
    includeUserId: true,
    includeState: true,
    page: "myBookMark"
);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return Value

Calling this method returns a Future&lt;(RtmStatus, GetOnlineUsersResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a GetOnlineUsersResult type data, which is defined as follows:
  class GetOnlineUsersResult {
      final List<UserState> userStateList; // List of user temporary states
      final int count; // Length of the user temporary state list
      final String nextPage; // Bookmark for the next page of data
  }

getUserChannels

Description

In use-cases such as statistic analytics and debugging, you may need to know all the channels that a specified user has subscribed to or joined. Call the getUserChannels method to get the list of channels where the specified user is in real time.

Method

You can call the getUserChannels method as follows:

Future<(RtmStatus, GetUserChannelsResult?)> getUserChannels(String userId);
ParametersTypeRequiredDefaultDescription
userIdStringRequired-User ID.

Basic usage

var (status, response) = await rtmClient.getPresence.getUserChannels("Tony");

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return Value

Calling this method returns a Future&lt;(RtmStatus, GetUserChannelsResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a GetUserChannelsResult type data, which is defined as follows:
  class GetUserChannelsResult {
      final List<ChannelInfo> channels; // List of channel information
      final int count; // Length of the user temporary state list
  }

setState

Description

To meet different requirements in different business use-cases for setting user states, Signaling provides the setState method to customize the temporary user state. Users can add custom states such as scores, game state, location, mood, and hosting state for themselves.

After successful setup, as long as the user keeps subscribing to the channel and stays online, the custom states can persist in the channel. The setState method sets the temporary user state, and the state disappears when the user leaves the channel. If you need to restore user states when rejoining a channel, you need to cache the data locally in real time. If you want to permanently save user states, Agora recommends you use the setUserMetadata method of the storage function instead.

If a user modifies the temporary user state, Signaling triggers the remoteStateChanged type of the presence event in real time. You can receive the event by subscribing to the channel and configuring the corresponding property.

Method

You can call the setState method as follows:

Future<(RtmStatus, SetStateResult?)> setState(
    String channelName,
    RtmChannelType channelType,
    Map<String, String> state
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
stateMap&lt;String, String&gt;Required-User state key-value pairs.

Basic usage

var states = {"Name":"Tony","Mode":"Happy"};
var (status, response) = await rtmClient.getPresence.setState(
    "myChannel",
    RtmChannelType.message,
    states
);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return Value

Calling this method returns a Future&lt;(RtmStatus, SetStateResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a SetStateResult type data, which currently does not contain any fields.

getState

Description

To get the temporary user state of a specified user in the channel, you can use the getState method.

Method

You can call the getState method as follows:

Future<(RtmStatus, GetStateResult?)> getState(
    String channelName,
    RtmChannelType channelType,
    String userId
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
userIdStringRequired-User ID.

Basic usage

var (state, response) = await rtmClient.getPresence.getState(
    "myChannel",
    RtmChannelType.message,
    "Tony"
);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return Value

Calling this method returns a Future&lt;(RtmStatus, GetStateResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a GetStateResult type data, which is defined as follows:
  class GetStateResult {
      final UserState state; // User temporary state data
  }

removeState

Description

When a temporary user state is no longer needed, you can call the removeState method to remove one or more of your temporary states. When the user state is removed, the user who has subscribed to the channel and enabled the presence event listener receives the remoteStateChanged type of presence event notification. See Event Listeners.

Method

You can call the removeState method as follows:

Future<(RtmStatus, RemoveStateResult?)> removeState(
    String channelName,
    RtmChannelType channelType,
    {
        List<String> states = const []
    }
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
statesList&lt;String&gt;Required-List of keys to be deleted. If you do not provide this property, the SDK removes all states.

Basic usage

var states = ["Mode", "Position"];
var (status, response) = await rtmClient.getPresence.removeState(
    "channelName",
    RtmChannelType.message,
    states
);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return Value

Calling this method returns a Future&lt;(RtmStatus, RemoveStateResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item in the tuple returns a RemoveStateResult type data, which currently does not contain any fields.

Storage

The storage feature provides a dynamic database mechanism that allows developers to dynamically set, store, update, and delete data such as channel metadata and user metadata.

RtmStorage Storage instance

setChannelMetadata

Description

The setChannelMetadata method sets metadata for a message channel or stream channel. A channel can only have one set of metadata, but each set of metadata can have one or more metadata items. If you call this method multiple times, the SDK retrieves the key of the metadata items in turn and apply settings according to the following rules:

  • If you set metadata with different key, the SDK adds each set of metadata in sequence according to the order of the method calls.
  • If you set metadata with the same key, the value of the last setting overwrites the previous one.

Channel metadata also introduces the version control logic CAS (Compare And Set). This method provides two independent version control fields, and you can set one or more of them according to your actual business use-case:

  • Enable version number verification for the entire set of channel metadata by setting the majorRevision property.
  • Enable version number verification for a single metadata item by setting the revision property in the MetadataItem class.

When setting channel metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:

  • The default value of the revision property is -1, indicating that this method call does not perform any CAS verification. If the channel metadata or metadata item already exists, the latest value overwrites the previous one. If the channel metadata or metadata item does not exist, the SDK creates it.
  • If the revision property is a positive integer, this method call performs the CAS verification. If the channel metadata or metadata item already exists, the SDK updates the corresponding value after the version number verification succeeds. If the channel metadata or metadata item does not exist, the SDK returns the error code.

After successfully setting channel metadata, users who subscribe to the channel and enable event listeners can receive the channel type of the storage event notification. See Event listeners.

Method

You can call the setChannelMetadata method as follows:

Future<(RtmStatus, SetChannelMetadataResult?)> setChannelMetadata(
    String channelName,
    RtmChannelType channelType,
    List<MetadataItem> metadata,
    {
        int majorRevision = -1,
        bool recordTs = false,
        bool recordUserId = false,
        String lockName = ''
    }
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequiredmessageChannel types. See RtmChannelType.
metadataList&lt;MetadataItem&gt;Required-Metadata item. See MetadataItem .
majorRevisionintOptional-1Version control switch:
- -1: Disable version verification.
- &gt; 0: Enable version verification, only execute the operation if the target version number matches this value.
recordTsboolOptionalfalseWhether to record the timestamp of the edits.
recordUserIdboolOptionalfalseWhether to record the user ID of the editor.
lockNameStringOptional''Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations.

The MetadataOptions data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
recordTsboolOptionalfalseWhether to record the timestamp of the edits.
recordUserIdboolOptionalfalseWhether to record the user ID of the editor.

Basic usage

var item1 = MetadataItem(
  key: 'Apple',
  value: '100',
  revision: 174298200
);

var item2 = MetadataItem(
  key: 'Banana',
  value: '200',
  revision: 174298100
);

var metadata = [item1,item2];

var (status,response) = await rtmClient.getStorage.setChannelMetadata(
    "myChannel",
    RtmChannelType.message,
    metadata,
    majorRevision: 174298222,
    recordTs: true,
    recordUserId: true,
    lockName: "myLock"
)

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Returns

Calling this method returns a Future&lt;(RtmStatus, SetChannelMetadataResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call is successful, the second item of the tuple returns a SetChannelMetadataResult type data, defined as follows:
  class SetChannelMetadataResult {
      final String channelName; // The channel being operated on
      final RtmChannelType channelType; // The type of the channel being operated on
  }

getChannelMetadata

Description

The getChannelMetadata method can get the metadata of the specified channel.

Method

You can call the getChannelMetadata method as follows:

Future<(RtmStatus, GetChannelMetadataResult?)> getChannelMetadata(
    String channelName,
    RtmChannelType channelType
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.

Basic usage

var (status,response) = await rtmClient.getStorage.getChannelMetadata(
    "myChannel",
    RtmChannelType.message,
)

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Returns

Calling this method returns a Future&lt;(RtmStatus, GetChannelMetadataResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call is successful, the second item of the tuple returns a GetChannelMetadataResult type data, defined as follows:
  class GetChannelMetadataResult {
      final String channelName; // The channel being operated on
      final RtmChannelType channelType; // The type of the channel being operated on
      final Metadata data; // Metadata data
  }

removeChannelMetadata

Description

The removeChannelMetadata method can remove channel metadata or metadata items.

When removing channel metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:

  • The default value of the revision property is -1, indicating that this method call does not perform any CAS verification. If the channel metadata or metadata item already exists, the SDK removes it. If the channel metadata or metadata item does not exist, the SDK returns an error code.
  • If the revision property is a positive integer, this method call performs the CAS verification. If the channel metadata or metadata item already exists, the SDK removes the corresponding value after the version number verification succeeds. If the channel metadata or metadata item does not exist, the SDK returns the error code.

After successfully removing channel metadata or metadata items, users who subscribe to the channel and enable event listeners can receive the channel type of the storage event notification. See Event listeners.

Method

You can call the removeChannelMetadata method as follows:

Future<(RtmStatus, RemoveChannelMetadataResult?)> removeChannelMetadata(
    String channelName,
    RtmChannelType channelType,
    {
        int majorRevision = -1,
        List<MetadataItem> metadata = const [],
        bool recordTs = false,
        bool recordUserId = false,
        String lockName = ''
    }
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
majorRevisionintOptional-1Version control switch:
- -1: Disable version verification.
- &gt; 0: Enable version verification, only execute the operation if the target version number matches this value.
metadataList&lt;MetadataItem&gt;Optional-Metadata item. See MetadataItem.
lockNameStringOptional''Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations.
recordTsboolOptionalfalseWhether to record the timestamp of the edits.
recordUserIdboolOptionalfalseWhether to record the user ID of the editor.

Basic usage

var item1 = MetadataItem(
  key: 'Apple',
  revision: 174298200
);

var item2 = MetadataItem(
  key: 'Banana',
  revision: 174298100
);

var metadata = [item1,item2];

var (status,response) = await rtmClient.getStorage.removeChannelMetadata(
    "myChannel",
    RtmChannelType.message,
    metadata,
    majorRevision: 174298222,
    recordTs: true,
    recordUserId: true,
    lockName: "myLock"
);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Returns

Calling this method returns a Future&lt;(RtmStatus, RemoveChannelMetadataResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call is successful, the second item of the tuple returns a RemoveChannelMetadataResult type data, defined as follows:
  class RemoveChannelMetadataResult {
      final String channelName; // The channel being operated on
      final RtmChannelType channelType; // The type of the channel being operated on
  }

updateChannelMetadata

Description

The updateChannelMetadata method can update existing channel metadata. Each time you call this method, you can update one channel metadata or a channel metadata item.

After successfully updating channel metadata, users who subscribe to the channel and enable event listeners can receive the channel type of the storage event notification. See Event listeners.

Information

You cannot use this method to update metadata items which do not exist.

Method

You can call the updateChannelMetadata method as follows:

Future<(RtmStatus, UpdateChannelMetadataResult?)> updateChannelMetadata(
    String channelName,
    RtmChannelType channelType,
    List<MetadataItem> metadata = const [],
    {
      int majorRevision = -1,
      bool recordTs = false,
      bool recordUserId = false,
      String lockName = ''
    }
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
metadataList&lt;MetadataItem&gt;Optional-Metadata item. See MetadataItem.
majorRevisionintOptional-1Version control switch:
- -1: Disable version verification.
- &gt; 0: Enable version verification, only execute the operation if the target version number matches this value.
recordTsboolOptionalfalseWhether to record the timestamp of the edits.
recordUserIdboolOptionalfalseWhether to record the user ID of the editor.
lockNameStringOptional''Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations.

Basic usage

var item1 = MetadataItem(
  key: 'Apple',
  value: '330',
  revision: 174298200
);

var item2 = MetadataItem(
  key: 'Banana',
  value: '480',
  revision: 174298100
);

var metadata = [item1,item2];

var (status,response) = await rtmClient.getStorage.updateChannelMetadata(
    "myChannel",
    RtmChannelType.message,
    metadata,
    majorRevision: 174298222,
    recordTs: true,
    recordUserId: true,
    lockName: "myLock"
);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Returns

Calling this method returns a Future&lt;(RtmStatus, UpdateChannelMetadataResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call is successful, the second item of the tuple returns a UpdateChannelMetadataResult type data, defined as follows:
  class UpdateChannelMetadataResult {
      final String channelName; // The channel being operated on
      final RtmChannelType channelType; // The type of the channel being operated on
  }

setUserMetadata

Description

The setUserMetadata method can set metadata for a user. If you call this method multiple times, the SDK retrieves the key of the metadata items in turn and apply settings according to the following rules:

  • If you set metadata with different key, the SDK adds each set of metadata in sequence according to the order of the method calls.
  • If you set metadata with the same key, the value of the last setting overwrites the previous one.

After successfully setting user metadata, users who subscribe to the user and enable event listeners can receive the user type of the storage event notification. See Event listeners.

User metadata also introduces the version control logic CAS (Compare And Set). This method provides two independent version control fields, and you can set one or more of them according to your actual business use-case:

  • Enable version number verification for the entire set of channel metadata by setting the majorRevision property.
  • Enable version number verification for a single metadata item by setting the revision property in the MetadataItem class.

When setting user metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:

  • The default value of the revision property is -1, indicating that this method call does not perform any CAS verification. If the user metadata or metadata item already exists, the latest value overwrites the previous one. If the user metadata or metadata item does not exist, the SDK creates it.
  • If the revision property is a positive integer, this method call performs the CAS verification. If the user metadata or metadata item already exists, the SDK updates the corresponding value after the version number verification succeeds. If the user metadata or metadata item does not exist, the SDK returns the error code.

After successfully setting user metadata, users who subscribe to the user and enable event listeners can receive the user type of the storage event notification. See Event listeners.

Method

You can call the setUserMetadata method as follows:

Future<(RtmStatus, SetUserMetadataResult?)> setUserMetadata(
    String userId,
    List<MetadataItem> metadata,
    {
        int majorRevision = -1,
        bool recordTs = false,
        bool recordUserId = false
    }
);
ParametersTypeRequiredDefaultDescription
userIdStringRequired-User ID.
metadataList&lt;MetadataItem&gt;Required-Metadata item. See MetadataItem.
majorRevisionintOptional-1The version control switch:
- -1: Disable the version verification.
- > 0: Enable the version verification. The operation can only be performed if the target version number matches this value.
recordTsboolOptionalfalseWhether to record the timestamp of the edits.
recordUserIdboolOptionalfalseWhether to record the user ID of the editor.

Basic usage

var item1 = MetadataItem(
  key: 'Name',
  value: 'Tony',
  revision: 174298200
);

var item2 = MetadataItem(
  key: 'Mute',
  value: 'true',
  revision: 174298100
);

var metadata = [item1,item2];

var (status,response) = await rtmClient.getStorage.setUserMetadata(
    "Tony",
    metadata,
    majorRevision: 174298222,
    recordTs: true,
    recordUserId: true
);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

This method returns a Future&lt;(RtmStatus, SetUserMetadataResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a SetUserMetadataResult object, defined as follows:
  class SetUserMetadataResult {
      final String userId; // The user ID of the current operation
  }

getUserMetadata

Description

The getUserMetadata method can get the metadata and metadata item for the specified user.

Method

You can call the getUserMetadata method as follows:

Future<(RtmStatus, GetUserMetadataResult?)> getUserMetadata(String userId);
ParametersTypeRequiredDefaultDescription
userIdStringRequired-User ID.

Basic usage

var (status,response) = await rtmClient.getStorage.getUserMetadata( "Tony" );

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

This method returns a Future&lt;(RtmStatus, GetUserMetadataResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a GetUserMetadataResult object, defined as follows:
  class GetUserMetadataResult {
      final String userId; // The user ID of the current operation
      final Metadata data; // User metadata
  }

removeUserMetadata

Description

The removeUserMetadata method can remove user metadata or metadata items.

After successfully removing user metadata, users who subscribe to the user and enable event listeners can receive the user type of the storage event notification. See Event listeners.

Method

You can call the removeUserMetadata method as follows:

Future<(RtmStatus, RemoveUserMetadataResult?)> removeUserMetadata(
    String userId,
    {
        int majorRevision = -1,
        List<MetadataItem> metadata = const [],
        bool recordTs = false,
        bool recordUserId = false
    }
);
ParametersTypeRequiredDefaultDescription
userIdStringRequired-User ID.
majorRevisionintOptional-1The version control switch:
- -1: Disable the version verification.
- > 0: Enable the version verification. The operation can only be performed if the target version number matches this value.
metadataList&lt;MetadataItem&gt;Optionalconst []Metadata item. See MetadataItem.
recordTsboolOptionalfalseWhether to record the timestamp of the edits.
recordUserIdboolOptionalfalseWhether to record the user ID of the editor.

Basic usage

var item1 = MetadataItem(
  key: 'Name',
  revision: 174298200
);

var item2 = MetadataItem(
  key: 'Mute',
  revision: 174298100
);

var metadata = [item1,item2];

var (status,response) = await rtmClient.getStorage.removeUserMetadata(
    "Tony",
    metadata: metadata
    majorRevision: 174298222,
    recordTs: true,
    recordUserId: true
);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

This method returns a Future&lt;(RtmStatus, RemoveUserMetadataResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a RemoveUserMetadataResult object, defined as follows:
  class RemoveUserMetadataResult {
      final String userId; // The user ID of the current operation
  }

updateUserMetadata

Description

The updateUserMetadata method can update existing user metadata.

After successfully updating channel metadata, users who subscribe to the user and enable event listeners can receive the user type of the storage event notification. See Event listeners.

Information

You cannot use this method to update metadata items which do not exist.

Method

You can call the updateUserMetadata method as follows:

Future<(RtmStatus, UpdateUserMetadataResult?)> updateUserMetadata(
    String userId,
    List<MetadataItem> metadata,
    {
        int majorRevision = -1,
        bool recordTs = false,
        bool recordUserId = false
    }
);
ParametersTypeRequiredDefaultDescription
userIdStringRequired-User ID.
metadataList&lt;MetadataItem&gt;Required-Metadata item. See MetadataItem.
majorRevisionintOptional-1The version control switch:
- -1: Disable the version verification.
- > 0: Enable the version verification. The operation can only be performed if the target version number matches this value.
recordTsboolOptionalfalseWhether to record the timestamp of the edits.
recordUserIdboolOptionalfalseWhether to record the user ID of the editor.

Basic usage

var item1 = MetadataItem(
  key: 'Name',
  value: 'Sara',
  revision: 174298200
);

var item2 = MetadataItem(
  key: 'Mute',
  value: 'false',
  revision: 174298100
);

var metadata = [item1,item2];

var (status,response) = await rtmClient.getStorage.updateUserMetadata(
    "Sara",
    metadata,
    majorRevision: 174298222,
    recordTs: true,
    recordUserId: true
);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

This method returns a Future&lt;(RtmStatus, UpdateUserMetadataResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a UpdateUserMetadataResult object, defined as follows:
  class UpdateUserMetadataResult {
      final String userId; // The user ID of the current operation
  }

subscribeUserMetadata

Description

The subscribeUserMetadata method can subscribe to metadata for a specified user.

After successfully subscribing to the user metadata, you can receive the user type of the storage event notification when the metadata for that user changes. See Event listeners.

Method

You can call the subscribeUserMetadata method as follows:

Future<(RtmStatus, SubscribeUserMetadataResult?)> subscribeUserMetadata(String userId);
ParametersTypeRequiredDefaultDescription
userIdStringRequired-User ID.

Basic usage

var (status,response) = await rtmClient.getStorage.subscribeUserMetadata( "Sara");

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

This method returns a Future&lt;(RtmStatus, SubscribeUserMetadataResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a SubscribeUserMetadataResult object, defined as follows:
  class SubscribeUserMetadataResult {
      final String userId; // The user ID of the current operation
  }

unsubscribeUserMetadata

Description

If you do not need to receive notifications of changes to a user metadata, call the unsubscribeUserMetadata method to unsubscribe.

Method

You can call the unsubscribeUserMetadata method as follows:

Future<(RtmStatus, UnsubscribeUserMetadataResult?)> unsubscribeUserMetadata(String userId);
ParametersTypeRequiredDefaultDescription
userIdStringRequired-User ID.

Basic usage

var (status,response) = await rtmClient.getStorage.unsubscribeUserMetadata( "Sara");

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

This method returns a Future&lt;(RtmStatus, UnsubscribeUserMetadataResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a UnsubscribeUserMetadataResult object, defined as follows:
  class UnsubscribeUserMetadataResult {
      final String userId; // The user ID of the current operation
  }

MetadataItem

Use the MetadataItem data type to set and manage metadata items, containing the following properties:

PropertiesTypeRequiredDefaultDescription
keyStringOptional-Key.
valueStringOptional-Value.
authorUserIdStringOptional-The user ID of the editor. This value is read-only and does not support writing.
revisionintOptional-1
- Returns the real version number in read operations.
- Serves as a version control switch in write operations:
- -1: Disable the version verification.
- > 0: Enable version verification, only perform the operation if the target version number matches this value.
updateTsintOptional0Update timestamp. This value is read-only and does not support writing.

Lock

A critical resource can only be used by one process at a time. If a critical resource is shared between different processes, each process needs to adopt a mutually exclusive method to prevent mutual interference. Signaling provides a full set of lock solutions. By controlling different processes in a distributed system, you can solve the competition problem when users access shared resources.

Information

The client is able to set, remove, and revoke locks. We recommend that you control the permissions of these operations on the client side based on your business needs.

RtmLock Lock instance

setLock

Description

You need to configure the lock name, time to live (TTL), and other parameters by calling the setLock method. If the configuration succeeds, all users in the channel receive the lock event notifications of the lockSet type. For details, see Event Listeners.

Method

You can call the setLock method as follows:

Future<(RtmStatus, SetLockResult?)> setLock(
    String channelName,
    RtmChannelType channelType,
    String lockName,
    {
        int? ttl = 10
    }
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
lockNameStringRequired-Lock name.
ttlintOptional10The expiration time of the lock. The value is in seconds, ranging from [10 to 300]. When the user who owns the lock goes offline, if the user returns to the channel within the time they can still use the lock; otherwise, the lock is released and the users who listen for the lock event receive the lockReleased event.

Basic usage

var (status,response) =
    await rtmClient.getLock.setLock( "myChannel", RtmChannelType.message, "myLock", ttl:15);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

Calling this method returns a Future&lt;(RtmStatus, SetLockResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a SetLockResult object, defined as follows:
  class SetLockResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final String lockName; // Lock name
  }

acquireLock

Description

After successfully configuring a lock, you can call the acquireLock method on the client to acquire the right to own the lock. When you acquire the lock, other users in the channel receive the lockAcquired type of the lock event. For details, see Event Listeners.

Method

You can call the acquireLock method as follows:

Future<(RtmStatus, AcquireLockResult?)> acquireLock(
    String channelName,
    RtmChannelType channelType,
    String lockName,
    {
        bool retry = false
    }
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
lockNameStringRequired-Lock name.
retryboolOptionalfalseIf the lock acquisition fails, whether to retry until the acquisition succeeds or the user leaves the channel.

Basic usage

var (status,response) =
    await rtmClient.getLock.acquireLock("myChannel", RtmChannelType.message, "myLock", retry:true);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

Calling this method returns a Future&lt;(RtmStatus, AcquireLockResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns an AcquireLockResult object, defined as follows:
  class AcquireLockResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final String lockName; // Lock name
      final String errorDetails; // Error details
  }

releaseLock

Description

When a user no longer needs to own a lock, the user can call the releaseLock method on the client side to release the lock. After successful release the lock, other users in the channel receive the lockReleased type of the lock event. See Event Listeners.

At this time, if other users want to acquire the lock, they can call the acquireLock method on the client side to compete. New users acquiring locks have the same contention priority as the users who set the retry property to automatically retry to acquire locks.

Method

You can call the releaseLock method as follows:

Future<(RtmStatus, ReleaseLockResult?)> releaseLock(
    String channelName,
    RtmChannelType channelType,
    String lockName
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
lockNameStringRequired-Lock name.

Basic usage

var (status,response) =
    await rtmClient.getLock.releaseLock("myChannel", RtmChannelType.message, "myLock");

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

Calling this method returns a Future&lt;(RtmStatus, ReleaseLockResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a ReleaseLockResult object, defined as follows:
  class ReleaseLockResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final String lockName; // Lock name
  }

revokeLock

Description

When the lock is occupied, to ensure that your business is not affected, you may need to revoke the lock and give other users a chance to obtain it. Revoke the occupied lock by calling revokeLock. When the lock is revoked, all users in the channel receive the lockReleased type of the lock event. See Event Listeners.

At this time, if other users want to acquire the lock, they can call the acquireLock method on the client side to compete. New users acquiring locks have the same contention priority as the users who set the retry property to automatically retry to acquire locks.

Method

You can call the revokeLock method as follows:

Future<(RtmStatus, RevokeLockResult?)> revokeLock(
    String channelName,
    RtmChannelType channelType,
    String lockName,
    String owner
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
lockNameStringRequired-Lock name.
ownerStringRequired-The ID of the user who has a lock.

Basic usage

var (status,response) = await rtmClient.getLock.revokeLock("myChannel", RtmChannelType.message, "myLock", "Tony");

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

Calling this method returns a Future&lt;(RtmStatus, RevokeLockResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a RevokeLockResult object, defined as follows:
  class RevokeLockResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final String lockName; // Lock name
  }

Description

If you want to query the lock information such as lock total number, lock name, lock user, and time to live, you can call the `` method on the client.

Method

You can call the `` method as follows:

Future<(RtmStatus, GetLocksResult?)> getLocks(
    String channelName,
    RtmChannelType channelType
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.

Basic usage

var (status,response) =
    await rtmClient.getLock.getLocks("myChannel", RtmChannelType.message);

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

Calling this method returns a Future&lt;(RtmStatus, GetLocksResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a GetLocksResult object, defined as follows:
  class GetLocksResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final List<LockDetail> lockDetailList; // Lock details
      final int count; // Lock count
  }

removeLock

Description

If you no longer need a lock, you can call the removeLock method to remove the lock. After successfully removing the lock, all users in the channel receive the lockRemoved type of lock event notification. See Event Listeners.

Method

You can call the removeLock method as follows:

Future<(RtmStatus, RemoveLockResult?)> removeLock(
    String channelName,
    RtmChannelType channelType,
    String lockName
);
ParametersTypeRequiredDefaultDescription
channelNameStringRequired-Channel name.
channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
lockNameStringRequired-Lock name.

Basic usage

var (status,response) =
    await rtmClient.getLock.removeLock("myChannel", RtmChannelType.message, "myLock");

if (status.error == true) {
    print(status);
} else {
    print(response);
}

Return

Calling this method returns a Future&lt;(RtmStatus, RemoveLockResult?)&gt; tuple data. Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

  • If the method call succeeds, the second item of the tuple returns a RemoveLockResult object, defined as follows:
  class RemoveLockResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final String lockName; // Lock name
  }

Enumerated types

Enum

RtmAreaCode

The region for connection, which is the region where the server the SDK connects to is located.

ValueDescription
cn0x00000001: Mainland China.
na0x00000002: North America.
eu0x00000004: Europe.
asm0x00000008: Asia, excluding Mainland China.
jp0x00000010: Japan.
ind0x00000020: India.
glob0xFFFFFFFF: Global.

RtmChannelType

Channel types.

ValueDescription
message1: Message channel.
stream2: Stream channel.
user3: User Channel.

RtmConnectionChangeReason

Reasons causing the change of the connection state.

ValueDescription
connecting0: The SDK is connecting with the server.
joinSuccess1: The SDK has joined the channel successfully.
interrupted2: The connection between the SDK and the server is interrupted.
bannedByServer3: The connection between the SDK and the server is banned by the server.
joinFailed4: The SDK fails to join the channel. When the SDK fails to join the channel for more than 20 minutes, this error occurs and the SDK stops reconnecting to the channel.
leaveChannel5: The SDK has left the channel.
invalidAppId6: The connection failed because the App ID is not valid.
invalidChannelName7: The connection failed because the channel name is not valid.
invalidToken8: The connection failed because the token is not valid.
tokenExpired9: The connection failed because the token is expired.
rejectedByServer10: The connection is rejected by server.
settingProxyServer11: The connection state changed to reconnecting because the SDK has set a proxy server.
renewToken12: The connection state changed because the token is renewed.
clientIpAddressChanged13: The IP address of the client has changed, possibly because the network type, IP address, or port has been changed.
keepAliveTimeout14: Timeout for the keep-alive of the connection between the SDK and the server. The connection state changes to reconnecting.
rejoinSuccess15: The user has rejoined the channel successfully.
lost16: The connection between the SDK and the server is lost.
echoTest17: The connection state changes due to the echo test.
clientIpAddressChangedByUser18: The local IP address was changed by the user. The connection state changes to reconnecting.
sameUidLogin19: The user joined the same channel from different devices with the same UID.
tooManyBroadcasters20: The number of hosts in the channel has reached the upper limit.
licenseValidationFailure21: The license validation failed.
certificationVerifyFailure22: The server certificate validation failed.
streamChannelNotAvailable23: The stream channel does not exist.
inconsistentAppid24: The App ID does not match the token.
loginSuccess10001: The SDK logs in to the Signaling system.
logout10002: The SDK logs out from the Signaling system.
presenceNotReady10003: Presence service is not ready. You need to call the login method again to log in to the Signaling system and re-execute all operations on the SDK.

RtmConnectionState

SDK connection states.

ValueDescription
disconnected1: The SDK has disconnected with the server.
connecting2: The SDK is connecting with the server.
connected3: The SDK has connected with the server.
reconnecting4: The connection is lost. The SDK is reconnecting with the server.
failed5: The SDK failed to connect with the server.

RtmLinkStateChangeReason

ValueDescription
unknown0: Unknown reason.
login1: Logging in.
loginSuccess2: Login successful.
loginTimeout3: Login timeout.
loginNotAuthorized4: Login not authorized.
loginRejected5: Login rejected.
relogin6: Re-login.
logout7: Logout.
autoReconnect8: Auto-reconnect.
reconnectTimeout9: Reconnect timeout.
reconnectSuccess10: Reconnect successful.
join11: Joining a channel.
joinSuccess12: Join channel successful.
joinFailed13: Join channel failed.
rejoin14: Re-join a channel.
leave15: Leave a channel.
invalidToken16: Invalid token.
tokenExpired17: Token expired.
inconsistentAppId18: Inconsistent app ID.
invalidChannelName19: Invalid channel name.
invalidUserId20: Invalid user ID.
notInitialized21: SDK not initialized.
rtmServiceNotConnected22: RTM service not connected.
channelInstanceExceedLimitation23: Channel instance exceeds the limit.
operationRateExceedLimitation24: Operation frequency exceeds the limit.
channelInErrorState25: Channel in error state.
presenceNotConnected26: Presence service not connected.
sameUidLogin27: Login with the same user ID.
kickedOutByServer28: Kicked out by the server.
keepAliveTimeout29: Keepalive timeout.
connectionError30: Connection error.
presenceNotReady31: Presence service not ready.
networkChange32: Network changed.
serviceNotSupported33: Service not supported.
streamChannelNotAvailable34: Stream Channel not available.
storageNotAvailable35: Storage service not available.
lockNotAvailable36: Lock service not available.
loginTooFrequent37: The login operation is too frequent.

RtmEncryptionMode

Encryption mode.

ValueDescription
none0: No encryption.
aes128Gcm1: AES-128-GCM mode.
aes256Gcm2: AES-256-GCM mode.

RtmLockEventType

Lock event type.

ValueDescription
snapshot1: The snapshot of the lock when the user joined the channel.
lockSet2: The lock is set.
lockRemoved3: The lock is removed.
lockAcquired4: The lock is acquired.
lockReleased5: The lock is released.
lockExpired6: The lock expired.

RtmLogLevel

Log output levels.

ValueDescription
none0x0000: No log.
info0x0001: Output the log at the FATAL, ERROR, WARN, or INFO level. We recommend you set to this value.
warn0x0002: Output the log at the FATAL, ERROR, WARN level.
error0x0004: Output the log at the FATAL, ERROR level.
fatal0x0008: Output the log at the FATAL level.

RtmMessagePriority

Message priority.

ValueDescription
highest0: Highest.
high1: High.
normal4: Normal.
low8: Low.

RtmMessageQos

QoS guarantee when sending topic messages.

ValueDescription
unordered0: Message data is not guaranteed to arrive in order.
ordered1: Message data arrives in order.

RtmMessageType

Message Type.

Enum ValueDescription
binary0: Binary type.
string1: String type.

RtmPresenceEventType

Presence event type.

ValueDescription
snapshot1: The snapshot of the presence when the user joined the channel.
interval2: When users in the channel reach the setting value, the event notifications are sent at intervals rather than in real time.
remoteJoinChannel3: A remote user joined the channel.
remoteLeaveChannel4: A remote user left the channel.
remoteTimeout5: A remote user's connection timed out.
remoteStateChanged6: A remote user's temporary state changed.
errorOutOfService7: The user did not enable presence when joining the channel.

RtmLinkOperation

Operation type.

ValueDescription
login0: The user logins to the Signaling system.
logout1: The user logouts of the Signaling system.
join2: The user joins in a stream channel.
leave3: The user leaves a stream channel.
serverReject4: The Signaling server reject the connection.
autoReconnect5: The SDK is automatically reconnecting to the Signaling server.
reconnected6: The SDK is reconnected to the Signaling server.
heartbeatLost7: The Signaling server does not receive the heartbeat packet within the specified timeout period.
serverTimeout8: The Signaling server has timed out.
networkChange9: The network status changes.

RtmLinkState

Link state type.

ValueDescription
idle0: The init state.
connecting1: Connecting.
connected2: Connected.
disconnected3: Disconnected.
suspended4: Suspended.
failed5: Failed.

RtmProtocolType

Protocol type.

ValueDescription
tcpUdp0: Both TCP and UDP protocols.
tcpOnly1: Only TCP protocol.

RtmServiceType

Service type

ValueDescription
messageThe foundational services comprise the message channel, user channel, presence, storage, and lock services.
streamThe stream channel service.

Information

To fully utilize all services offered by Signaling, you can employ bitwise operations to simultaneously configure two service types.

RtmProxyType

Proxy type.

ValueDescription
none0: Do not enable the proxy.
http1: Enable the proxy for the HTTP protocol.
cloudTcp2: Enable the cloud proxy for the TCP protocol.

RtmStorageEventType

Storage event type.

ValueDescription
snapshot1: When a user subscribes to channel metadata or user etadata for the first time, or joins a channel, the local user receives notifications of this type of event.
set2: Occurs when calling setChannelMetadata or setUserMetadata. Caution: This event only occurs in incremental data update mode.
update3: Occurs when calling methods to set, update, or delete the channel metadata or user metadata.
remove4: Occurs when calling removeChannelMetadata or removeUserMetadata. Caution: This event only occurs in incremental data update mode.

RtmStorageType

Storage type.

ValueDescription
user1: User metadata event.
channel2: Channel metadata event.

RtmTopicEventType

Topic event type.

ValueDescription
snapshot1: The snapshot of the topic when the user joined the channel.
remoteJoinTopic2: A remote user joined the channel.
remoteLeaveTopic3: A remote user left the channel.

Troubleshooting

Refer to the following information for troubleshooting API calls.

ErrorInfo

Regardless of whether the method call succeeds, the first item in the tuple always returns RtmStatus data type, with the fields defined as follows:

class RtmStatus {
    bool error; // Indicates whether there was an error in this operation.
    String errorCode; // The error code for this operation.
    String operation; // The operation.
    String reason; // A brief description of the error reason for this operation.
}

You can understand the error reason and find the corresponding solution by looking up the error codes in the error codes table.

Error codes table

Refer to the following error codes table to identify and troubleshoot the problem:

Error codeError descriptionCause and solution
0okCorrect call
-10001notInitializedThe SDK is not initialized. Please initialize the RtmClient instance by calling the createAgoraRtmClient method before performing other operations.
-10002notLoginThe user called the API without logging in to Signaling, disconnected due to timeout, or actively logged out. Please log in to Signaling first.
-10003invalidAppIdInvalid App ID:
- Check that the App ID is correct.
- Ensure that Signaling has been activated for the App ID.
-10005invalidTokenInvalid Token:
- The token is invalid, check whether the Token Provider generates a valid Signaling Token.
-10006invalidUserIdInvalid User ID:
- Check if user ID is empty.
- Check if the user ID contains illegal characters.
-10007initServiceFailedSDK initialization failed. Please reinitialize by calling the createAgoraRtmClient method.
-10008invalidChannelNameInvalid channel name:
- Check if the channel name is empty.
- Check if the channel name contains illegal characters.
-10009tokenExpiredToken expired. Call renewToken to reacquire the Token.
-10010loginNoServerResourcesServer resources are limited. It is recommended to log in again.
-10011loginTimeoutLogin timeout. Check whether the current network is stable and switch to a stable network environment.
-10012loginRejectedSDK login rejected by the server:
- Check tha Signaling is activated on your App ID.
- Check if the token or userId is banned.
-10013loginAbortedSDK login interrupted due to unknown problem:
- Check that the current network is stable and switch to a stable network environment.
- The current userId is logged in.
-10014invalidParameterInvalid parameter. Please check if the parameters you provided are correct.
-10015loginNotAuthorizedNo RTM service permissions. Check that the console opens Signaling services.
-10016inconsistentAppidInconsistent App ID. Please check whether the App ID used for initialization, login, and joining a channel are consistent.
-10017duplicateOperationDuplicate operation.
-10018instanceAlreadyReleasedRepeat rtm instantiation or RTMStreamChannel instantiation.
-10019invalidChannelTypeInvalid channel type. The SDK only supports the following channel types. Please use the correct value:
- message: Message Channel
- stream: Stream Channel
- user: User Channel
-10020invalidEncryptionParameterMessage encryption parameters are invalid.
- Check that the encryption key generated is a String.
- Check that the generated encryption salt is Uint8Array type and that the length is 32 bytes.
- Check that the encryption method matches the encryption key and the encryption salt.
-10021operationRateExceedLimitationChannel metadata or User Metadata -related API call frequency is exceeding the limit. Please control the call frequency within 10/second.
-10022serviceNotSupportedThe service type is not supported. Check whether the service type you set in RtmServiceType is correct. This error code is only applicable to the private deployment function.
-10023loginCanceledThe login operation has been canceled. Possible reasons are as follows:
- After calling the login method, if you call the method again before receiving the call result, the previous call operation will be canceled and the SDK will execute the next call.
- Calling the logout method to log out before successfully logging in.
-10024invalidPrivateConfigThe private deployment parameter settings are invalid. Please check whether the service type and server address you set in RtmPrivateConfig are valid.
-10025notConnectedNot connected to the Signaling server.
-10026renewTokenTimeoutToken renewal timed out.
-11001channelNotJoinedThe user has not joined the channel:
- The user is not online, offline or has not joined the channel
- Check for typos in userId.
-11002channelNotSubscribedThe user has not subscribed to the channel:
- The user is not online, offline or has not joined the channel
- Check for typos in userId.
-11003channelExceedTopicUserLimitationThe number of subscribers to this topic exceeds the limit.
-11004channelInReuseIn co-channel mode, RTM released the Stream Channel.
-11005channelInstanceExceedLimitationThe number of created or subscribed channels exceeds the limit. See API usage limits for details.
-11006channelInErrorStateChannel is not available. Please recreate the Stream Channel or resubscribe to the Message Channel.
-11007channelJoinFailedFailed to join this channel:
- Check if the number of joined channels exceeds the limit.
- Check if the channel name is illegal.
- Check if the network is disconnected.
-11008channelInvalidTopicNameInvalid topic name:
- Check whether the topic name contains illegal characters.
- Check if the topic name is empty.
-11009channelInvalidMessageInvalid message. Check whether the message type is legal, Signaling only supports string, Uint8Array type messages.
-11010channelMessageLengthExceedLimitationMessage length exceeded limit. Check if the message payload size exceeds the limit:
- Message Channel single message package limit is 32 KB.
- Stream Channel single message package limit is 1 KB.
-11011channelInvalidUserListInvalid user list:
- Check if the user list is empty.
- Check if the user list contains invalid entries.
-11012channelNotAvailableInvalid user list:
- Check if the user list is empty
- Check if the user list contains illegal items.
-11013channelTopicNotSubscribedThe topic is not subscribed.
-11014channelExceedTopicLimitationThe number of topics exceeds the limit.
-11015channelJoinTopicFailedFailed to join this topic. Check whether the number of added topics exceeds the limit.
-11016channelTopicNotJoinedThe topic has not been joined. To send a message, you need to join the Topic first.
-11017channelTopicNotExistThe topic does not exist. Check that the topic name is correct.
-11018channelInvalidTopicMetaThe meta parameters in the topic are invalid. Check if the meta parameter exceeds 256 bytes.
-11019channelSubscribeTimeoutChannel subscription timed out. Check for broken connections.
-11020channelSubscribeTooFrequentThe channel subscription operation is too frequent. Make sure that the subscription operation of the same channel within a 5 seconds interval does not exceed 2 attempts.
-11021channelSubscribeFailedChannel subscription failed. Check if the number of subscribed channels exceeds the limit.
-11022channelUnsubscribeFailedFailed to unsubscribe from the channel. Check if the connection is disconnected.
-11023channelEncryptMessageFailedMessage encryption failed:
- Check that the cipherKey is valid.
- Check that the salt is valid.
- Check if encryptionMode mode matches the cipherKey and salt.
-11024channelPublishMessageFailedMessage publishing failed. Check for broken connections.
-11026channelPublishMessageTimeoutMessage publishing timed out. Check for broken connections.
-11027channelNotConnectedThe SDK is disconnected from the Signaling server. Please log in again.
-11028channelLeaveFailedFailed to leave the channel. Check for broken connections.
-11029channelCustomTypeLengthOverflowCustom type length overflow. The length of the customType field must to be within 32 characters.
-11030channelInvalidCustomTypecustomType field is invalid. Check the customType field for illegal characters.
-11031channelUnsupportedMessageTypeMessage type is not supported.
-11032channelPresenceNotReadyPresence service is not ready. Please rejoin the Stream Channel or resubscribe to the Message Channel.
-11033channelReceiverOfflineWhen sending a user message, the remote user is offline:
- Check if the user ID set when calling the method is correct.
- Check if the remote user is logged in and online.
-11034channelJoinCanceledThe join channel operation has been canceled. After calling the joinTopic method, if you call the method again before receiving the call result, the previous call operation will be canceled and the SDK will execute the next call.
-12001storageOperationFailedStorage operation failed.
-12002storageMetadataItemExceedLimitationThe number of Storage Metadata Items exceeds the limit.
-12003storageInvalidMetadataItemInvalid Metadata Item.
-12004storageInvalidArgumentInvalid argument.
-12005storageInvalidRevisionInvalid Revision parameter.
-12006storageMetadataLengthOverflowMetadata overflows.
-12007storageInvalidLockNameInvalid Lock name.
-12008storageLockNotAcquiredThe Lock was not acquired.
-12009storageInvalidKeyInvalid Metadata key.
-12010storageInvalidValueInvalid metadata value.
-12011storageKeyLengthOverflowMetadata key length overflow.
-12012storageValueLengthOverflowMetadata value length overflow.
-12013storageDuplicateKeyDuplicate Metadata Item key.
-12014storageOutdatedRevisionOutdated Revision parameter.
-12015storageNotSubscribeThis channel is not subscribed.
-12016storageInvalidMetadataInstanceMetadata instance does not exist. Please create a Metadata instance.
-12017storageSubscribeUserExceedLimitationThe number of subscribers exceeds the limit.
-12018storageOperationTimeoutStorage operation timed out.
-12019storageNotAvailableThe Storage service is not available.
-13001presenceNotConnectedThe user is not connected to the system.
-13002presenceNotWritablePresence service is unavailable.
-13003presenceInvalidArgumentInvalid argument.
-13004presenceCachedTooManyStatesThe temporary user state cached before joining the channel exceeds the limit. See API usage limits for details.
-13005presenceStateCountOverflowThe number of temporary user state key/value pairs exceeds the limit. See API usage limits for details.
-13006presenceInvalidStateKeyInvalid state key.
-13007presenceInvalidStateValueInvalid state value.
-13008presenceStateKeySizeOverflowPresence key length overflow.
-13009presenceStateValueSizeOverflowPresence value overflow
-13010presenceStateDuplicateKeyRepeated state key.
-13011presenceUserNotExistThe user does not exist.
-13012presenceOperationTimeoutPresence operation timed out.
-13013presenceOperationFailedPresence operation failed.
-14001lockOperationFailedLock operation failed.
-14002lockOperationTimeoutLock operation timed out.
-14003lockOperationPerformingLock operation in progress.
-14004lockAlreadyExistLock already exists.
-14005lockInvalidNameInvalid Lock name.
-14006lockNotAcquiredThe Lock was not acquired.
-14007lockAcquireFailedFailed to acquire the Lock.
-14008lockNotExistThe Lock does not exist.
-14009lockNotAvailableLock service is not available.