# Flutter (/en/api-reference/api-ref/signaling/flutter)

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

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

* [Setup](#setup)
* [User authentication](#user-authentication)
* [Channels](#channels)
* [Topics](#topics)
* [Messages](#messages)
* [Presence](#presence)
* [Storage](#storage)
* [Lock](#lock)
* [Enumerated types](#enumerated-types)
* [Troubleshooting](#troubleshooting)

## Setup [#setup]

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

### RtmConfig [#rtmconfig]

#### Description [#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 [#method]

You can create `RtmConfig` instances as follows:

```dart
RtmConfig({
    int heartbeatInterval,
    int presenceTimeout,
    bool useStringUserId,
    bool ispPolicyEnabled,
    RtmProtocolType protocolType,
    RtmLogConfig logConfig,
    RtmProxyConfig proxyConfig,
    RtmEncryptionConfig encryptionConfig,
    RtmPrivateConfig privateConfig,
    Set<RtmAreaCode> areaCode
})
```

|      Properties     |          Type         | Required |  Default | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| :-----------------: | :-------------------: | :------: | :------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|      `areaCode`     |     `RtmAreaCode`     | Optional |  `glob`  | Service area code, you can choose according to the region where your business is deployed. See [`RtmAreaCode`](#enumvareacod-e).                                                                                                                                                                                                                                                                                                                                                               |
|    `protocolType`   |   `RtmProtocolType`   | Optional | `tcpUdp` | Protocol 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`](#enumvprotocoltyp-e).                                                                                                                                                                                                                             |
|  `presenceTimeout`  |          int          | Optional |   `300`  | Presence 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. |
| `heartbeatInterval` |          int          | Optional |    `5`   | Heartbeat 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.                                                         |
|  `useStringUserId`  |          bool         | Optional |  `true`  | Whether to use string-type user IDs:<br />- `true`: Use string-type user IDs. <br />- `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.                                         |
|  `ispPolicyEnabled` |          bool         | Optional |  `false` | Whether 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.                                                                                                                                                                                                                                                                                                                     |
|     `logConfig`     |     `RtmLogConfig`    | Optional |     -    | Log configuration properties such as the log storage size, storage path, and level.                                                                                                                                                                                                                                                                                                                                                                                                            |
|    `proxyConfig`    |    `RtmProxyConfig`   | Optional |     -    | When using the Proxy feature of Signaling, you need to configure this parameter.                                                                                                                                                                                                                                                                                                                                                                                                               |
|  `encryptionConfig` | `RtmEncryptionConfig` | Optional |     -    | When using the client-side encryption feature of Signaling, you need to configure this parameter.                                                                                                                                                                                                                                                                                                                                                                                              |
|   `privateConfig`   |   `RtmPrivateConfig`  | Optional |     -    | When using the private deployment feature of Signaling, you need to configure this parameter.                                                                                                                                                                                                                                                                                                                                                                                                  |

##### RtmLogConfig [#rtmlogconfig]

```dart
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:

|   Properties   |      Type     | Required | Default | Description                                                                                                                                                                                                                |
| :------------: | :-----------: | :------: | :-----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `filePath`   |     String    | Optional |    -    | Log file storage paths.                                                                                                                                                                                                    |
| `fileSizeInKB` |      int      | Optional |  `1024` | Log file size in KB, with a value range of \[128,1024].<br />- If the value you enter is less than 128, the SDK sets the value to 128.<br />- If the value you enter is greater than 1024, the SDK sets the value to 1024. |
|     `level`    | `RtmLogLevel` | Optional |  `info` | Output level of log information. See [`RtmLogLevel`](#enumvlogleve-l).                                                                                                                                                     |

##### RtmProxyConfig [#rtmproxyconfig]

```dart
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.

<CalloutContainer type="warning">
  <CalloutTitle>
    Caution
  </CalloutTitle>

  <CalloutDescription>
    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.
  </CalloutDescription>
</CalloutContainer>

`RtmProxyConfig` contains the following properties:

|  Properties |      Type      | Required | Default | Description                                                  |
| :---------: | :------------: | :------: | :-----: | ------------------------------------------------------------ |
| `proxyType` | `RtmProxyType` | Optional |  `none` | Proxy protocol type. See [`RtmProxyType`](#enumvproxytyp-e). |
|   `server`  |     String     | Optional |    -    | Proxy server domain name or IP address.                      |
|    `port`   |       int      | Optional |   `0`   | Proxy listening port.                                        |
|  `account`  |     String     | Optional |    -    | Proxy login account.                                         |
|  `password` |     String     | Optional |    -    | Proxy login password.                                        |

##### RtmEncryptionConfig [#rtmencryptionconfig]

```dart
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.

<CalloutContainer type="warning">
  <CalloutTitle>
    Caution
  </CalloutTitle>

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

`RtmEncryptionConfig` contains the following properties:

|      Properties     |         Type        | Required | Default | Description                                                                                                           |
| :-----------------: | :-----------------: | :------: | :-----: | --------------------------------------------------------------------------------------------------------------------- |
|   `encryptionMode`  | `RtmEncryptionMode` | Optional |  `none` | Encryption mode. See [`RtmEncryptionMode`](#enumvencryptionmod-e).                                                    |
|   `encryptionKey`   |        String       | Optional |    -    | User-defined encryption key, unlimited length. Agora recommends using a 32-byte key.                                  |
| `encryptionKdfSalt` |      Uint8List      | Optional |  `null` | User-defined encryption salt, length is 32 bytes. Agora recommends using OpenSSL to generate salt on the server side. |

##### RtmPrivateConfig [#rtmprivateconfig]

```dart
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:

|     Properties     |             Type            | Required | Default | Description                                                                       |
| :----------------: | :-------------------------: | :------: | :-----: | --------------------------------------------------------------------------------- |
|    `serviceType`   | `Set&lt;RtmServiceType&gt;` | Optional |    -    | Service type. See [`RtmServiceType`](#enumvrtmservicetyp-e).                      |
| `accessPointHosts` |     `List&lt;String&gt;`    | Optional |    -    | An array of server addresses, where you can fill in domain names or IP addresses. |

#### Basic usage [#basic-usage]

```dart
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 [#initialization]

#### Description [#description-1]

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

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    <br />- You need to create and initialize a client instance before calling other Signaling APIs. <br />- 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.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-1]

You can create and initialize an instance as follows:

```dart
Future<(RtmStatus,RtmClient)> RTM(
    String appId,
    String userId,
    {
        RtmConfig rtmConfig
    }
)
```

|  Parameters |     Type    | Required | Default | Description                                                                                                                                                                                                        |
| :---------: | :---------: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|   `appId`   |    String   | Required |    -    | App ID obtained when creating a project in the Agora Console.                                                                                                                                                      |
|   `userId`  |    String   | Required |    -    | 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. |
| `rtmConfig` | `RtmConfig` | Optional |    -    | Initialize the configuration parameters of the Signaling Client. See `RtmConfig`.                                                                                                                                  |

#### Basic usage [#basic-usage-1]

```dart
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 [#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:

```dart
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).

* 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 [#event-listeners]

#### Description [#description-2]

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

|  Event Type | Description                                                                                                                                                               |
| :---------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|  `message`  | Receive message event notifications in subscribed message channels and subscribed topics.                                                                                 |
|  `presence` | Receive presence event notifications in subscribed message channels and joined stream channels.                                                                           |
|   `topic`   | Receive all topic event notifications in joined stream channels.                                                                                                          |
|  `storage`  | Receive channel metadata event notifications in subscribed message channels and joined stream channels, and the user metadata event notification of the subscribed users. |
|    `lock`   | Receive lock event notifications in subscribed message channels and joined stream channels.                                                                               |
| `linkState` | Receive event notifications when client connection status changes. For details, see [`LinkStateEvent`](#configlinkstateeven-t).                                           |
|   `token`   | Receive event notifications when the client tokens are about to expire.                                                                                                   |

#### Add event listeners [#add-event-listeners]

You can add an event listener object as follows:

```dart
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 [#remove-event-listeners]

You can remove an event listener object as follows:

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

##### MessageEvent [#messageevent]

Message event.

`MessageEvent` contains the following properties:

|    Properties   |       Type       | Description                                                |
| :-------------: | :--------------: | ---------------------------------------------------------- |
|  `channelType`  | `RtmChannelType` | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e). |
|  `messageType`  | `RtmMessageType` | Message type. See [`RtmMessageType`](#enumvmessagetyp-e).  |
|  `channelName`  |      String      | Channel name.                                              |
|  `channelTopic` |      String      | Topic name.                                                |
|    `message`    |     Uint8List    | Message.                                                   |
| `messageLength` |        int       | Message length.                                            |
|   `publisher`   |      String      | User ID of the message publisher.                          |
|   `customType`  |      String      | A user-defined field. Only supports string type.           |
|   `timestamp`   |        int       | The timestamp when the event occurs.                       |

##### PresenceEvent [#presenceevent]

User presence event.

`PresenceEvent` contains the following properties:

|   Properties  |           Type          | Description                                                                                                                                                                                   |
| :-----------: | :---------------------: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     `type`    |  `RtmPresenceEventType` | Presence event type. See [`RtmPresenceEventType`](#enumvpresencetyp-e).                                                                                                                       |
| `channelType` |     `RtmChannelType`    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                                                                                    |
| `channelName` |          String         | Channel name.                                                                                                                                                                                 |
|  `publisher`  |          String         | User ID of the message publisher.                                                                                                                                                             |
|  `stateItems` | `List&lt;StateItem&gt;` | Key-value pair that identifies the user's presence state.                                                                                                                                     |
|   `interval`  |      `IntervalInfo`     | In 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. |
|   `snapshot`  |      `SnapshotInfo`     | When 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.                                                |
|  `timestamp`  |           int           | The timestamp when the event occurs.                                                                                                                                                          |

`StateItem` data type contains the following properties:

| Properties |  Type  | Description                                                                                                                                                        |
| :--------- | :----: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`      | String | Key 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. |
| `value`    | String | Value of the user state.                                                                                                                                           |

`IntervalInfo` contains the following properties:

| Properties        |           Type          | Description                                                                                                |
| :---------------- | :---------------------: | :--------------------------------------------------------------------------------------------------------- |
| `joinUserList`    |        `UserList`       | List of users who joined the channel in the previous cycle.                                                |
| `leaveUserList`   |        `UserList`       | List of users who left the channel in the previous cycle.                                                  |
| `timeoutUserList` |        `UserList`       | List of users who timed out joining the channel in the previous cycle.                                     |
| `userStateList`   | `List&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:

| Properties      |           Type          | Description                                                                                                       |
| :-------------- | :---------------------: | :---------------------------------------------------------------------------------------------------------------- |
| `userStateList` | `List&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:

| Properties |         Type         | Description |
| :--------- | :------------------: | :---------: |
| `users`    | `List&lt;String&gt;` |  User list. |

`UserState` contains the following properties:

| Properties |           Type          |                                     Description                                    |
| :--------- | :---------------------: | :--------------------------------------------------------------------------------: |
| `userId`   |          String         |                                      User ID.                                      |
| `states`   | `List&lt;StateItem&gt;` | List of online users and their temporary state information in a specified channel. |

##### TopicEvent [#topicevent]

Topic event.

`TopicEvent` contains the following properties:

|   Properties  |           Type          | Description                                                    |
| :-----------: | :---------------------: | -------------------------------------------------------------- |
|     `type`    |   `RtmTopicEventType`   | Topic event type. See [`RtmTopicEventType`](#enumvtopictyp-e). |
| `channelName` |          String         | Channel name.                                                  |
|  `publisher`  |          String         | User ID.                                                       |
|  `topicInfos` | `List&lt;TopicInfo&gt;` | Topic information.                                             |
|  `timestamp`  |           int           | The timestamp when the event occurs.                           |

`TopicInfo` data type contains the following properties:

|  Properties  |             Type            | Description              |
| :----------: | :-------------------------: | ------------------------ |
|    `topic`   |            String           | Topic name.              |
| `publishers` | `List&lt;PublisherInfo&gt;` | Message publisher array. |

`PublisherInfo` data type contains the following properties:

|     Properties    |  Type  | Description                        |
| :---------------: | :----: | ---------------------------------- |
| `publisherUserId` | String | User ID of the message publisher.  |
|  `publisherMeta`  | String | Metadata of the message publisher. |

##### StorageEvent [#storageevent]

Storage event.

`StorageEvent` contains the following properties:

|   Properties  |          Type         | Description                                                               |
| :-----------: | :-------------------: | ------------------------------------------------------------------------- |
| `channelType` |    `RtmChannelType`   | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                |
| `storageType` |    `RtmStorageType`   | Storage type. See [`RtmStorageType`](#enumvstoragetyp-e).                 |
|  `eventType`  | `RtmStorageEventType` | Storage event type. See [`RtmStorageEventType`](#enumvstorageeventtyp-e). |
|    `target`   |         String        | User ID or channel name.                                                  |
|     `data`    |          `*`          | Metadata item. See [\`\`](../storage#IMetadata).                          |
|  `timestamp`  |          int          | The timestamp when the event occurs.                                      |

##### LockEvent [#lockevent]

Lock event.

`LockEvent` contains the following properties:

|    Properties    |           Type           | Description                                                 |
| :--------------: | :----------------------: | ----------------------------------------------------------- |
|   `channelType`  |     `RtmChannelType`     | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).  |
|    `eventType`   |    `RtmLockEventType`    | Lock event type. See [`RtmLockEventType`](#enumvlocktyp-e). |
|   `channelName`  |          String          | Channel name.                                               |
| `lockDetailList` | `List&lt;LockDetail&gt;` | Details of lock.                                            |
|      `count`     |            int           | Lock count.                                                 |
|    `timestamp`   |            int           | The timestamp when the event occurs.                        |

The `LockDetail` data type contains the following properties:

| Properties |  Type  | Description                                                                                                                                                                                                                                                                                                                         |
| :--------- | :----: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `lockName` | String | Lock name.                                                                                                                                                                                                                                                                                                                          |
| `owner`    | String | The ID of the user who has a lock.                                                                                                                                                                                                                                                                                                  |
| `ttl`      |   int  | The 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 [#linkstateevent]

SDK link state event.

`LinkStateEvent` data type contains the following properties:

|      Parameters      |         Type         | Description                                                                                                                                                                                                         |
| :------------------: | :------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|    `currentState`    |    `RtmLinkState`    | The current link state. See [`RtmLinkState`](#enumvlinkstat-e).                                                                                                                                                     |
|    `previousState`   |    `RtmLinkState`    | The previous link state. See [`RtmLinkState`](#enumvlinkstat-e).                                                                                                                                                    |
|     `serviceType`    |   `RtmServiceType`   | The network connection type. See [`RtmServiceType`](#enumvrtmservicetyp-e).                                                                                                                                         |
|      `operation`     |  `RtmLinkOperation`  | The operation that triggered the current state transition. See [`RtmLinkOperation`](#enumvlinkoperatio-n).                                                                                                          |
|       `reason`       |        String        | The reason of the current state transition. See [`RtmLinkStateChangeReason`](#enumvlinkstatereaso-n).                                                                                                               |
|  `affectedChannels`  | `List&lt;String&gt;` | The channels affected by the current state transition.                                                                                                                                                              |
| `unrestoredChannels` | `List&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. |
|      `isResumed`     |         bool         | Within 2 minutes of the disconnection, whether the state transitions from `disconnected` to `connected`. `true` refers to the state has transitioned.                                                               |
|      `timestamp`     |          int         | The timestamp when the event occurs.                                                                                                                                                                                |

RtmClient
Signaling client instance.

### login [#login]

#### Description [#description-3]

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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

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

#### Method [#method-2]

You can log in to the Signaling system as follows:

```dart
Future<(RtmStatus, LoginResult?)> login(String token);
```

| Parameters |  Type  | Required | Default | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| :--------: | :----: | :------: | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `token`  | String | Required |    -    | The token used for logging into the Signaling system.<br />- If your project enables token authentication, you can provide either the [Signaling temporary token](https://agora-token-generator-demo.vercel.app/) or the Signaling token generated by your token server. See [User authentication](/en/realtime-media/rtm/build/connect-and-authenticate/authentication-workflow) and [Deploy Signaling token generator](https://github.com/AgoraIO/Tools/tree/master/DynamicKey/AgoraDynamicKey).<br />- 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 [#basic-usage-2]

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

#### Return value [#return-value-1]

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:

```dart
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).

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

### logout [#logout]

#### Description [#description-4]

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 [#method-3]

You can log out as follows:

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

#### Basic usage [#basic-usage-3]

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

#### Return value [#return-value-2]

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:

```dart
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).

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

### releaseLock [#releaselock]

#### Description [#description-5]

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 [#method-4]

You can destroy the `RtmClient` instance as follows:

```dart
Future<RtmStatus> release();
```

#### Basic usage [#basic-usage-4]

```dart
var status = await rtmClient.release();
```

#### Return value [#return-value-3]

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

```dart
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](/signaling/reference/error-codes) to understand the cause of the error and find the corresponding solution.

## User authentication [#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](/en/realtime-media/rtm/build/connect-and-authenticate/authentication-workflow).

### renewToken [#renewtoken]

#### Description [#description-6]

To ensure timely token updates, Agora recommends listening for the `token` callback. See [Event listeners](#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 [#method-5]

You can call the `renewToken` method as follows:

```dart
Future<(RtmStatus, RenewTokenResult?)> renewToken(String token);
```

| Parameters |  Type  | Required | Default | Description                                                                                                                                                                                                                              |
| :--------: | :----: | :------: | :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `token`  | String | Required |    -    | Fill in the corresponding token in this parameter according to the type of service you use.<br />- For the `MESSAGE` service, fill in a newly generated RTM token.<br />- For the `STREAM` service, fill in a newly generated RTC token. |

#### Basic Usage [#basic-usage-5]

```dart
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 [#return-value-4]

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:

```dart
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).

* If the method call is successful, the second item in the tuple returns data of type `RenewTokenResult`, defined as follows:

```dart
  class RenewTokenResult {
      final RtmServiceType serverType; // Service type
      final String channelName; // Channel name
  }
```

## Channels [#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 [#subscribetopic]

#### Description [#description-7]

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](#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](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to message channels.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-6]

You can call the `subscribeTopic` method as follows:

```dart
Future<(RtmStatus, SubscribeResult?)> subscribe(
    String channelName,
    {
        bool withMessage = true,
        bool withMetadata = false,
        bool withPresence = true,
        bool withLock = false,
        bool beQuiet = false
    }
);
```

|   Parameters   |  Type  | Required | Default | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| :------------: | :----: | :------: | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|  `channelName` | String | Required |    -    | Channel name.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
|  `withMessage` |  bool  | Optional |  `true` | Whether to subscribe to message event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `withPresence` |  bool  | Optional |  `true` | Whether to subscribe to presence event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `withMetadata` |  bool  | Optional | `false` | Whether to subscribe to storage event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
|   `withLock`   |  bool  | Optional | `false` | Whether to subscribe to lock event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
|    `beQuiet`   |  bool  | Optional | `false` | Whether to set the silent mode. If you set this parameter as `true`, the SDK has the following behaviors:<br />- You can still receive other users' event notifications.<br />- 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.<br />- When calling the `getOnlineUsers` method, your information can not be found.<br />- When calling the `getUserChannels` method, channels that you subscribe in silent mode can not be detected. |

#### Basic usage [#basic-usage-6]

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

#### Return value [#return-value-5]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `SubscribeResult` type data, defined as follows:

```dart
  class SubscribeResult {
      final String channelName; // The channel of the current operation
  }
```

### unsubscribeTopic [#unsubscribetopic]

#### Description [#description-8]

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](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to message channels.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-7]

You can call the `unsubscribeTopic` method as follows:

```dart
Future<(RtmStatus, UnsubscribeResult?)> unsubscribe(String channelName);
```

|   Parameters  |  Type  | Required | Default | Description   |
| :-----------: | :----: | :------: | :-----: | ------------- |
| `channelName` | String | Required |    -    | Channel name. |

#### Basic usage [#basic-usage-7]

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

#### Return value [#return-value-6]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple will return a `UnsubscribeResult` type data, defined as follows:

```dart
  class UnsubscribeResult {
      final String channelName; // The channel of the current operation
  }
```

### createAgoraRtmClient [#createagorartmclient]

#### Description [#description-9]

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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to stream channels.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-8]

You can call the `createAgoraRtmClient` method as follows:

```dart
Future<(RtmStatus, StreamChannel?)> createStreamChannel(String channelName);
```

|   Parameters  |  Type  | Required | Default | Description   |
| :-----------: | :----: | :------: | :-----: | ------------- |
| `channelName` | String | Required |    -    | Channel name. |

#### Basic usage [#basic-usage-8]

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

#### Return value [#return-value-7]

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:

```dart
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).

* 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 [#jointopic]

#### Description [#description-10]

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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to stream channels.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-9]

You can call the `joinTopic` method as follows:

```dart
Future<(RtmStatus, JoinResult?)> join({
    String? token,
    bool withMetadata = false,
    bool withPresence = true,
    bool withLock = false,
    bool beQuiet = false
    }
);
```

|   Parameters   |  Type  | Required | Default | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| :------------: | :----: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     `token`    | String | Optional |    -    | The token used for joining a stream channel.<br />- If your project enables token authentication, you can provide either the [RTC temporary token](https://agora-token-generator-demo.vercel.app/) or the [RTC token](/en/realtime-media/rtm/build/connect-and-authenticate/authentication-workflow) generated by your token server.<br />- 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.                                                                                                   |
| `withPresence` |  bool  | Optional |  `true` | Whether to subscribe to presence event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `withMetadata` |  bool  | Optional | `false` | Whether to subscribe to storage event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
|   `withLock`   |  bool  | Optional | `false` | Whether to subscribe to lock event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
|    `beQuiet`   |  bool  | Optional | `false` | Whether to set the silent mode. If you set this parameter as `true`, the SDK has the following behaviors:<br />- You can still receive other users' event notifications.<br />- 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.<br />- When calling the `getOnlineUsers` method, your information can not be found.<br />- When calling the `getUserChannels` method, channels that you subscribe in silent mode can not be detected. |

#### Basic usage [#basic-usage-9]

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

#### Return value [#return-value-8]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple will return a `JoinResult` type data, defined as follows:

```dart
  class JoinResult {
      final String channelName; // The channel of the current operation
      final String userId; // The user ID of the current operation
  }
```

### leaveTopic [#leavetopic]

#### Description [#description-11]

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](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to stream channels.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-10]

You can call the `leaveTopic` method as follows:

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

#### Basic usage [#basic-usage-10]

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

#### Return value [#return-value-9]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple will return a `LeaveResult` type data, defined as follows:

```dart
  class LeaveResult {
      final String channelName; // The channel of the current operation
      final String userId; // The user ID of the current operation
  }
```

### releaseLock [#releaselock-1]

#### Description [#description-12]

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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    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.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-11]

You can call the `releaseLock` method as follows:

```dart
Future<RtmStatus> release();
```

#### Basic usage [#basic-usage-11]

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

#### Return value [#return-value-10]

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

```dart
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](/signaling/reference/error-codes) to understand the cause of the error and find the corresponding solution.

## Topics [#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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    Topics only exist in stream channels. Therefore, before using relevant features, you need to create the `StreamChannel` instance.
  </CalloutDescription>
</CalloutContainer>

StreamChannel
Stream channel instance

### joinTopic [#jointopic-1]

#### Description [#description-13]

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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    * 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.
  </CalloutDescription>
</CalloutContainer>

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](#event-listeners).

#### Method [#method-12]

You can call the `joinTopic` method as follows:

```dart
Future<(RtmStatus, JoinTopicResult?)> joinTopic(
    String topic,
    {
        RtmMessageQos qos = RtmMessageQos.unordered,
        RtmMessagePriority priority = RtmMessagePriority.normal,
        String? meta = '',
        bool? syncWithMedia = false
    }
);
```

|    Parameters   |         Type         | Required |   Default   | Description                                                                                                                               |
| :-------------: | :------------------: | :------: | :---------: | ----------------------------------------------------------------------------------------------------------------------------------------- |
|     `topic`     |        String        | Required |      -      | Topic name.                                                                                                                               |
|      `qos`      |    `RtmMessageQos`   | Optional | `unordered` | Whether the data transmitted in the topic is ordered. See [`RtmMessageQos`](#enumvmessageqo-s).                                           |
|    `priority`   | `RtmMessagePriority` | Optional |   `normal`  | The priority of data transmission in the topic compared to other topics in the same channel. See [`RtmMessagePriority`](#enumvpriorit-y). |
|      `meta`     |        String        | Optional |      -      | Adds additional metadata when joining the topic.                                                                                          |
| `syncWithMedia` |         bool         | Optional |   `false`   | Whether the data sent in this topic is synchronized (timestamp-aligned) with the RTC audio and video data stream of the common channel.   |

#### Basic usage [#basic-usage-12]

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

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

#### Return value [#return-value-11]

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:

```dart
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).

* If the method call succeeds, the second item in the tuple returns a `JoinTopicResult` object, defined as follows:

```dart
  class JoinTopicResult {
      final String channelName; // Channel name
      final String userId; // Current userId
      final String topic; // Topic name
      final String meta; // Additional metadata
  }
```

### publishTextMessage [#publishtextmessage]

#### Description [#description-14]

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](#setup).

#### Method [#method-13]

You can call the `publishTextMessage` method as follows:

```dart
Future<(RtmStatus, PublishTopicMessageResult?)> publishTextMessage(
    String topic,
    String message,
    {
        int sendTs = 0,
        String? customType
    }
);
```

|  Parameters  |  Type  | Required | Default | Description                                                                                                                                                                                                                 |
| :----------: | :----: | :------: | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|    `topic`   | String | Required |    -    | Topic name.                                                                                                                                                                                                                 |
|   `message`  | String | Required |    -    | Message payload.                                                                                                                                                                                                            |
|   `sendTs`   |   int  | Optional |   `0`   | The 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. |
| `customType` | String | Optional |    -    | A user-defined field. Only supports string type.                                                                                                                                                                            |

#### Basic usage [#basic-usage-13]

```dart
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 [#return-value-12]

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:

```dart
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).

* If the method call succeeds, the second item in the tuple returns a `PublishTopicMessageResult` object, defined as follows:

```dart
  class PublishTopicMessageResult {
      final String channelName; // Channel name
      final String topic; // Topic name
  }
```

### publishBinaryMessage [#publishbinarymessage]

#### Description [#description-15]

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](#setup).

#### Method [#method-14]

You can call the `publishBinaryMessage` method as follows:

```dart
Future<(RtmStatus, PublishTopicMessageResult?)> publishBinaryMessage(
    String topic,
    Uint8List message,
    {
        int sendTs = 0,
        String? customType
    }
);
```

|  Parameters  |    Type   | Required | Default | Description                                                                                                                                                                                                                 |
| :----------: | :-------: | :------: | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|    `topic`   |   String  | Required |    -    | Topic name.                                                                                                                                                                                                                 |
|   `message`  | Uint8List | Required |    -    | Message payload.                                                                                                                                                                                                            |
|   `sendTs`   |    int    | Optional |   `0`   | The 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. |
| `customType` |   String  | Optional |    -    | A user-defined field. Only supports string type.                                                                                                                                                                            |

#### Basic usage [#basic-usage-14]

```dart
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 [#return-value-13]

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:

```dart
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).

* If the method call succeeds, the second item in the tuple returns a `PublishTopicMessageResult` object, defined as follows:

```dart
  class PublishTopicMessageResult {
      final String channelName; // Channel name
      final String topic; // Topic name
  }
```

### leaveTopic [#leavetopic-1]

#### Description [#description-16]

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](#event-listeners).

#### Method [#method-15]

You can call the `leaveTopic` method as follows:

```dart
Future<(RtmStatus, LeaveTopicResult?)> leaveTopic(String topic);
```

| Parameters |  Type  | Required | Default | Description |
| :--------: | :----: | :------: | :-----: | ----------- |
|   `topic`  | String | Required |    -    | Topic name. |

#### Basic usage [#basic-usage-15]

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

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

#### Return value [#return-value-14]

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:

```dart
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).

* If the method call succeeds, the second item in the tuple returns a `LeaveTopicResult` object, defined as follows:

```dart
  class LeaveTopicResult {
      final String channelName; // Channel name
      final String userId; // User ID
      final String topic; // Topic name
      final String meta; // Additional metadata
  }
```

### subscribeTopic [#subscribetopic-1]

#### Description [#description-17]

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](/en/realtime-media/rtm/reference/limitations).

#### Method [#method-16]

You can call the `subscribeTopic` method as follows:

```dart
Future<(RtmStatus, SubscribeTopicResult?)> subscribeTopic(
    String topic,
    {
        List<String> users = const []
    }
);
```

| Parameters |         Type         | Required | Default | Description                                                                                                                                                       |
| :--------: | :------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `topic`  |        String        | Required |    -    | Topic name.                                                                                                                                                       |
|   `users`  | `List&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 [#basic-usage-16]

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

```dart
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.

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

#### Return value [#return-value-15]

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:

```dart
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).

* If the method call succeeds, the second item in the tuple returns a `SubscribeTopicResult` object, defined as follows:

```dart
  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 [#unsubscribetopic-1]

#### Description [#description-18]

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 [#method-17]

You can call the `unsubscribeTopic` method as follows:

```dart
Future<(RtmStatus, UnsubscribeTopicResult?)> unsubscribeTopic(
    String topic,
    {
        List<String> users = const []
    }
);
```

| Parameters |         Type         | Required | Default | Description                                                                                                                                                    |
| :--------: | :------------------: | :------: | :-----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `topic`  |        String        | Required |    -    | Topic name.                                                                                                                                                    |
|   `users`  | `List&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 [#basic-usage-17]

Example 1: Unsubscribe the specified message publisher in the topic

```dart
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

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

#### Return value [#return-value-16]

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:

```dart
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).

* If the method call succeeds, the second item in the tuple returns a `UnsubscribeTopicResult` object, defined as follows:

```dart
  class UnsubscribeTopicResult {
      final String channelName; // Channel name
      final String topic; // Topic name
  }
```

### getSubscribedUserList [#getsubscribeduserlist]

#### Description [#description-19]

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

#### Method [#method-18]

You can call the `getSubscribedUserList` method as follows:

```dart
Future<(RtmStatus, GetSubscribedUserListResult?)> getSubscribedUserList(String topic);
```

| Parameters |  Type  | Required | Default | Description |
| :--------: | :----: | :------: | :-----: | ----------- |
|   `topic`  | String | Required |    -    | Topic name. |

#### Basic usage [#basic-usage-18]

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

#### Return value [#return-value-17]

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:

```dart
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).

* If the method call succeeds, the second item in the tuple returns a `GetSubscribedUserListResult` object, defined as follows:

```dart
  class GetSubscribedUserListResult {
      final String channelName; // Channel name
      final String topic; // Topic name
      final UserList users; // List of successfully subscribed users
  }
```

## Messages [#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 [#publishtextmessage-1]

#### Description [#description-20]

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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    The following practices can effectively improve the reliability of message transmission:<br />- The message payload should be within 32 KB; otherwise, the sending will fail. <br />- 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.
  </CalloutDescription>
</CalloutContainer>

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](#event-listeners).

#### Method [#method-19]

You can call the `publishTextMessage` method as follows:

```dart
Future<(RtmStatus, PublishResult?)> publish(
    String channelName,
    String message,
    {
        RtmChannelType channelType = RtmChannelType.message,
        String? customType
    }
);
```

|   Parameters  |       Type       | Required |  Default  | Description                                                                                                                |
| :-----------: | :--------------: | :------: | :-------: | -------------------------------------------------------------------------------------------------------------------------- |
| `channelName` |      String      | Required |     -     | 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. |
|   `message`   |      String      | Required |     -     | Message payload.                                                                                                           |
| `channelType` | `RtmChannelType` | Optional | `message` | Channel type. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                  |
|  `customType` |      String      | Optional |     -     | A user-defined field. Only supports string type.                                                                           |

#### Basic usage [#basic-usage-19]

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

```dart
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.

```dart
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 [#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:

```dart
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).

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

### publishBinaryMessage [#publishbinarymessage-1]

#### Description [#description-21]

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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    The following practices can effectively improve the reliability of message transmission:<br />- The message payload should be within 32 KB; otherwise, the sending will fail. <br />- 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.
  </CalloutDescription>
</CalloutContainer>

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](#event-listeners).

#### Method [#method-20]

You can call the `publishBinaryMessage` method as follows:

```dart
Future<PublishResult> publishBinaryMessage(
    String channelName,
    Uint8List message,
    {
        RtmChannelType channelType = RtmChannelType.message,
        String? customType
    }
);
```

|   Parameters  |       Type       | Required |  Default  | Description                                                                                                                |
| :-----------: | :--------------: | :------: | :-------: | -------------------------------------------------------------------------------------------------------------------------- |
| `channelName` |      String      | Required |     -     | 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. |
|   `message`   |     Uint8List    | Required |     -     | Message payload.                                                                                                           |
| `channelType` | `RtmChannelType` | Optional | `message` | Channel type. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                  |
|  `customType` |      String      | Optional |     -     | A user-defined field. Only supports string type.                                                                           |

#### Basic usage [#basic-usage-20]

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

```dart
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.

```dart
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 [#return-values-1]

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:

```dart
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).

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

### Receive [#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:

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

<CalloutContainer type="info">
  <CalloutTitle>
    Message Format Conversion
  </CalloutTitle>

  <CalloutDescription>
    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:

    ```dart
    // convert Uint8List to String. ! means forced conversion
    String message = utf8.decode(event.message!);
    ```
  </CalloutDescription>
</CalloutContainer>

For information on how to add and set event listeners, see [Event Listeners](#event-listeners).

## Presence [#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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    **Presence** applies to both message channels and stream channels.
  </CalloutDescription>
</CalloutContainer>

RtmPresence
Presence instance

### getOnlineUsers [#getonlineusers]

#### Description [#description-22]

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 [#method-21]

You can call the `getOnlineUsers` method as follows:

```dart
Future<(RtmStatus, WhoNowResult?) whoNow(
    String channelName,
    RtmChannelType channelType,
    {
        bool includeUserId = true,
        bool includeState = false,
        String? page = ''
    }
);
```

|    Parameters   |       Type       | Required | Default | Description                                                                                                                                                                          |
| :-------------: | :--------------: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|  `channelName`  |      String      | Required |    -    | Channel name.                                                                                                                                                                        |
|  `channelType`  | `RtmChannelType` | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                                                                           |
| `includeUserId` |       bool       | Optional |  `true` | Whether the returned result includes the user ID of online members.                                                                                                                  |
|  `includeState` |       bool       | Optional | `false` | Whether the returned result includes temporary state data of online users.                                                                                                           |
|      `page`     |      String      | Optional |    -    | 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 [#basic-usage-21]

```dart
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 [#return-value-18]

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:

```dart
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).

* If the method call succeeds, the second item in the tuple returns a `GetOnlineUsersResult` type data, which is defined as follows:

```dart
  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 [#getuserchannels]

#### Description [#description-23]

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 [#method-22]

You can call the `getUserChannels` method as follows:

```dart
Future<(RtmStatus, GetUserChannelsResult?)> getUserChannels(String userId);
```

| Parameters |  Type  | Required | Default | Description |
| :--------: | :----: | :------: | :-----: | ----------- |
|  `userId`  | String | Required |    -    | User ID.    |

#### Basic usage [#basic-usage-22]

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

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

#### Return Value [#return-value-19]

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:

```dart
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).

* If the method call succeeds, the second item in the tuple returns a `GetUserChannelsResult` type data, which is defined as follows:

```dart
  class GetUserChannelsResult {
      final List<ChannelInfo> channels; // List of channel information
      final int count; // Length of the user temporary state list
  }
```

### setState [#setstate]

#### Description [#description-24]

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 [#method-23]

You can call the `setState` method as follows:

```dart
Future<(RtmStatus, SetStateResult?)> setState(
    String channelName,
    RtmChannelType channelType,
    Map<String, String> state
);
```

|   Parameters  |             Type            | Required | Default | Description                                                |
| :-----------: | :-------------------------: | :------: | :-----: | ---------------------------------------------------------- |
| `channelName` |            String           | Required |    -    | Channel name                                               |
| `channelType` |       `RtmChannelType`      | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e). |
|    `state`    | `Map&lt;String, String&gt;` | Required |    -    | User state key-value pairs.                                |

#### Basic usage [#basic-usage-23]

```dart
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 [#return-value-20]

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:

```dart
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).

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

### getState [#getstate]

#### Description [#description-25]

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

#### Method [#method-24]

You can call the `getState` method as follows:

```dart
Future<(RtmStatus, GetStateResult?)> getState(
    String channelName,
    RtmChannelType channelType,
    String userId
);
```

|   Parameters  |       Type       | Required | Default | Description                                                |
| :-----------: | :--------------: | :------: | :-----: | ---------------------------------------------------------- |
| `channelName` |      String      | Required |    -    | Channel name.                                              |
| `channelType` | `RtmChannelType` | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e). |
|    `userId`   |      String      | Required |    -    | User ID.                                                   |

#### Basic usage [#basic-usage-24]

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

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

#### Return Value [#return-value-21]

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:

```dart
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).

* If the method call succeeds, the second item in the tuple returns a `GetStateResult` type data, which is defined as follows:

```dart
  class GetStateResult {
      final UserState state; // User temporary state data
  }
```

### removeState [#removestate]

#### Description [#description-26]

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](#event-listeners).

#### Method [#method-25]

You can call the `removeState` method as follows:

```dart
Future<(RtmStatus, RemoveStateResult?)> removeState(
    String channelName,
    RtmChannelType channelType,
    {
        List<String> states = const []
    }
);
```

|   Parameters  |         Type         | Required | Default | Description                                                                                  |
| :-----------: | :------------------: | :------: | :-----: | -------------------------------------------------------------------------------------------- |
| `channelName` |        String        | Required |    -    | Channel name                                                                                 |
| `channelType` |   `RtmChannelType`   | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                   |
|    `states`   | `List&lt;String&gt;` | Required |    -    | List of keys to be deleted. If you do not provide this property, the SDK removes all states. |

#### Basic usage [#basic-usage-25]

```dart
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 [#return-value-22]

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:

```dart
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).

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

## Storage [#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 [#setchannelmetadata]

#### Description [#description-27]

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](#event-listeners).

#### Method [#method-26]

You can call the `setChannelMetadata` method as follows:

```dart
Future<(RtmStatus, SetChannelMetadataResult?)> setChannelMetadata(
    String channelName,
    RtmChannelType channelType,
    List<MetadataItem> metadata,
    {
        int majorRevision = -1,
        bool recordTs = false,
        bool recordUserId = false,
        String lockName = ''
    }
);
```

|    Parameters   |            Type            | Required |  Default  | Description                                                                                                                                                                                   |
| :-------------: | :------------------------: | :------: | :-------: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|  `channelName`  |           String           | Required |     -     | Channel name.                                                                                                                                                                                 |
|  `channelType`  |      `RtmChannelType`      | Required | `message` | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                                                                                    |
|    `metadata`   | `List&lt;MetadataItem&gt;` | Required |     -     | Metadata item. See [`MetadataItem `](#storagemetadataite-m).                                                                                                                                  |
| `majorRevision` |             int            | Optional |    `-1`   | Version control switch: <br />- `-1`: Disable version verification.<br />- `&gt; 0`: Enable version verification, only execute the operation if the target version number matches this value. |
|    `recordTs`   |            bool            | Optional |  `false`  | Whether to record the timestamp of the edits.                                                                                                                                                 |
|  `recordUserId` |            bool            | Optional |  `false`  | Whether to record the user ID of the editor.                                                                                                                                                  |
|    `lockName`   |           String           | Optional |     ''    | 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:

|   Properties   | Type | Required | Default | Description                                   |
| :------------: | :--: | :------: | :-----: | --------------------------------------------- |
|   `recordTs`   | bool | Optional | `false` | Whether to record the timestamp of the edits. |
| `recordUserId` | bool | Optional | `false` | Whether to record the user ID of the editor.  |

#### Basic usage [#basic-usage-26]

```dart
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 [#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:

```dart
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).

* If the method call is successful, the second item of the tuple returns a `SetChannelMetadataResult` type data, defined as follows:

```dart
  class SetChannelMetadataResult {
      final String channelName; // The channel being operated on
      final RtmChannelType channelType; // The type of the channel being operated on
  }
```

### getChannelMetadata [#getchannelmetadata]

#### Description [#description-28]

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

#### Method [#method-27]

You can call the `getChannelMetadata` method as follows:

```dart
Future<(RtmStatus, GetChannelMetadataResult?)> getChannelMetadata(
    String channelName,
    RtmChannelType channelType
);
```

|   Parameters  |       Type       | Required | Default | Description                                                |
| :-----------: | :--------------: | :------: | :-----: | ---------------------------------------------------------- |
| `channelName` |      String      | Required |    -    | Channel name.                                              |
| `channelType` | `RtmChannelType` | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e). |

#### Basic usage [#basic-usage-27]

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

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

#### Returns [#returns-1]

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:

```dart
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).

* If the method call is successful, the second item of the tuple returns a `GetChannelMetadataResult` type data, defined as follows:

```dart
  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 [#removechannelmetadata]

#### Description [#description-29]

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](#event-listeners).

#### Method [#method-28]

You can call the `removeChannelMetadata` method as follows:

```dart
Future<(RtmStatus, RemoveChannelMetadataResult?)> removeChannelMetadata(
    String channelName,
    RtmChannelType channelType,
    {
        int majorRevision = -1,
        List<MetadataItem> metadata = const [],
        bool recordTs = false,
        bool recordUserId = false,
        String lockName = ''
    }
);
```

|    Parameters   |            Type            | Required | Default | Description                                                                                                                                                                                   |
| :-------------: | :------------------------: | :------: | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|  `channelName`  |           String           | Required |    -    | Channel name.                                                                                                                                                                                 |
|  `channelType`  |      `RtmChannelType`      | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                                                                                    |
| `majorRevision` |             int            | Optional |   `-1`  | Version control switch: <br />- `-1`: Disable version verification.<br />- `&gt; 0`: Enable version verification, only execute the operation if the target version number matches this value. |
|    `metadata`   | `List&lt;MetadataItem&gt;` | Optional |    -    | Metadata item. See [`MetadataItem`](#storagemetadataite-m).                                                                                                                                   |
|    `lockName`   |           String           | Optional |    ''   | Lock name. If set, only users who call the `acquireLock` method to acquire the lock can perform operations.                                                                                   |
|    `recordTs`   |            bool            | Optional | `false` | Whether to record the timestamp of the edits.                                                                                                                                                 |
|  `recordUserId` |            bool            | Optional | `false` | Whether to record the user ID of the editor.                                                                                                                                                  |

#### Basic usage [#basic-usage-28]

```dart
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 [#returns-2]

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:

```dart
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).

* If the method call is successful, the second item of the tuple returns a `RemoveChannelMetadataResult` type data, defined as follows:

```dart
  class RemoveChannelMetadataResult {
      final String channelName; // The channel being operated on
      final RtmChannelType channelType; // The type of the channel being operated on
  }
```

### updateChannelMetadata [#updatechannelmetadata]

#### Description [#description-30]

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](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    You cannot use this method to update metadata items which do not exist.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-29]

You can call the `updateChannelMetadata` method as follows:

```dart
Future<(RtmStatus, UpdateChannelMetadataResult?)> updateChannelMetadata(
    String channelName,
    RtmChannelType channelType,
    List<MetadataItem> metadata = const [],
    {
      int majorRevision = -1,
      bool recordTs = false,
      bool recordUserId = false,
      String lockName = ''
    }
);
```

|    Parameters   |            Type            | Required | Default | Description                                                                                                                                                                                   |
| :-------------: | :------------------------: | :------: | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|  `channelName`  |           String           | Required |    -    | Channel name.                                                                                                                                                                                 |
|  `channelType`  |      `RtmChannelType`      | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                                                                                    |
|    `metadata`   | `List&lt;MetadataItem&gt;` | Optional |    -    | Metadata item. See [`MetadataItem`](#storagemetadataite-m).                                                                                                                                   |
| `majorRevision` |             int            | Optional |   `-1`  | Version control switch: <br />- `-1`: Disable version verification.<br />- `&gt; 0`: Enable version verification, only execute the operation if the target version number matches this value. |
|    `recordTs`   |            bool            | Optional | `false` | Whether to record the timestamp of the edits.                                                                                                                                                 |
|  `recordUserId` |            bool            | Optional | `false` | Whether to record the user ID of the editor.                                                                                                                                                  |
|    `lockName`   |           String           | Optional |    ''   | Lock name. If set, only users who call the `acquireLock` method to acquire the lock can perform operations.                                                                                   |

#### Basic usage [#basic-usage-29]

```dart
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 [#returns-3]

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:

```dart
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).

* If the method call is successful, the second item of the tuple returns a `UpdateChannelMetadataResult` type data, defined as follows:

```dart
  class UpdateChannelMetadataResult {
      final String channelName; // The channel being operated on
      final RtmChannelType channelType; // The type of the channel being operated on
  }
```

### setUserMetadata [#setusermetadata]

#### Description [#description-31]

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](#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](#event-listeners).

#### Method [#method-30]

You can call the `setUserMetadata` method as follows:

```dart
Future<(RtmStatus, SetUserMetadataResult?)> setUserMetadata(
    String userId,
    List<MetadataItem> metadata,
    {
        int majorRevision = -1,
        bool recordTs = false,
        bool recordUserId = false
    }
);
```

|    Parameters   |            Type            | Required | Default | Description                                                                                                                                                                                                    |
| :-------------: | :------------------------: | :------: | :-----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     `userId`    |           String           | Required |    -    | User ID.                                                                                                                                                                                                       |
|    `metadata`   | `List&lt;MetadataItem&gt;` | Required |    -    | Metadata item. See [`MetadataItem`](#storagemetadataite-m).                                                                                                                                                    |
| `majorRevision` |             int            | Optional |    -1   | The version control switch:<br />- `-1`: Disable the version verification.<br />- > `0`: Enable the version verification. The operation can only be performed if the target version number matches this value. |
|    `recordTs`   |            bool            | Optional | `false` | Whether to record the timestamp of the edits.                                                                                                                                                                  |
|  `recordUserId` |            bool            | Optional | `false` | Whether to record the user ID of the editor.                                                                                                                                                                   |

#### Basic usage [#basic-usage-30]

```dart
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 [#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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `SetUserMetadataResult` object, defined as follows:

```dart
  class SetUserMetadataResult {
      final String userId; // The user ID of the current operation
  }
```

### getUserMetadata [#getusermetadata]

#### Description [#description-32]

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

#### Method [#method-31]

You can call the `getUserMetadata` method as follows:

```dart
Future<(RtmStatus, GetUserMetadataResult?)> getUserMetadata(String userId);
```

| Parameters |  Type  | Required | Default | Description |
| :--------: | :----: | :------: | :-----: | ----------- |
|  `userId`  | String | Required |    -    | User ID.    |

#### Basic usage [#basic-usage-31]

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

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

#### Return [#return-1]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `GetUserMetadataResult` object, defined as follows:

```dart
  class GetUserMetadataResult {
      final String userId; // The user ID of the current operation
      final Metadata data; // User metadata
  }
```

### removeUserMetadata [#removeusermetadata]

#### Description [#description-33]

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](#event-listeners).

#### Method [#method-32]

You can call the `removeUserMetadata` method as follows:

```dart
Future<(RtmStatus, RemoveUserMetadataResult?)> removeUserMetadata(
    String userId,
    {
        int majorRevision = -1,
        List<MetadataItem> metadata = const [],
        bool recordTs = false,
        bool recordUserId = false
    }
);
```

|    Parameters   |            Type            | Required |   Default  | Description                                                                                                                                                                                                    |
| :-------------: | :------------------------: | :------: | :--------: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     `userId`    |           String           | Required |      -     | User ID.                                                                                                                                                                                                       |
| `majorRevision` |             int            | Optional |     -1     | The version control switch:<br />- `-1`: Disable the version verification.<br />- > `0`: Enable the version verification. The operation can only be performed if the target version number matches this value. |
|    `metadata`   | `List&lt;MetadataItem&gt;` | Optional | `const []` | Metadata item. See [`MetadataItem`](#storagemetadataite-m).                                                                                                                                                    |
|    `recordTs`   |            bool            | Optional |   `false`  | Whether to record the timestamp of the edits.                                                                                                                                                                  |
|  `recordUserId` |            bool            | Optional |   `false`  | Whether to record the user ID of the editor.                                                                                                                                                                   |

#### Basic usage [#basic-usage-32]

```dart
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 [#return-2]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `RemoveUserMetadataResult` object, defined as follows:

```dart
  class RemoveUserMetadataResult {
      final String userId; // The user ID of the current operation
  }
```

### updateUserMetadata [#updateusermetadata]

#### Description [#description-34]

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](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    You cannot use this method to update metadata items which do not exist.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-33]

You can call the `updateUserMetadata` method as follows:

```dart
Future<(RtmStatus, UpdateUserMetadataResult?)> updateUserMetadata(
    String userId,
    List<MetadataItem> metadata,
    {
        int majorRevision = -1,
        bool recordTs = false,
        bool recordUserId = false
    }
);
```

|    Parameters   |            Type            | Required | Default | Description                                                                                                                                                                                                    |
| :-------------: | :------------------------: | :------: | :-----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     `userId`    |           String           | Required |    -    | User ID.                                                                                                                                                                                                       |
|    `metadata`   | `List&lt;MetadataItem&gt;` | Required |    -    | Metadata item. See [`MetadataItem`](#storagemetadataite-m).                                                                                                                                                    |
| `majorRevision` |             int            | Optional |    -1   | The version control switch:<br />- `-1`: Disable the version verification.<br />- > `0`: Enable the version verification. The operation can only be performed if the target version number matches this value. |
|    `recordTs`   |            bool            | Optional | `false` | Whether to record the timestamp of the edits.                                                                                                                                                                  |
|  `recordUserId` |            bool            | Optional | `false` | Whether to record the user ID of the editor.                                                                                                                                                                   |

#### Basic usage [#basic-usage-33]

```dart
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 [#return-3]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `UpdateUserMetadataResult` object, defined as follows:

```dart
  class UpdateUserMetadataResult {
      final String userId; // The user ID of the current operation
  }
```

### subscribeUserMetadata [#subscribeusermetadata]

#### Description [#description-35]

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](#event-listeners).

#### Method [#method-34]

You can call the `subscribeUserMetadata` method as follows:

```dart
Future<(RtmStatus, SubscribeUserMetadataResult?)> subscribeUserMetadata(String userId);
```

| Parameters |  Type  | Required | Default | Description |
| :--------: | :----: | :------: | :-----: | ----------- |
|  `userId`  | String | Required |    -    | User ID.    |

#### Basic usage [#basic-usage-34]

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

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

#### Return [#return-4]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `SubscribeUserMetadataResult` object, defined as follows:

```dart
  class SubscribeUserMetadataResult {
      final String userId; // The user ID of the current operation
  }
```

### unsubscribeUserMetadata [#unsubscribeusermetadata]

#### Description [#description-36]

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

#### Method [#method-35]

You can call the `unsubscribeUserMetadata` method as follows:

```dart
Future<(RtmStatus, UnsubscribeUserMetadataResult?)> unsubscribeUserMetadata(String userId);
```

| Parameters |  Type  | Required | Default | Description |
| :--------: | :----: | :------: | :-----: | ----------- |
|  `userId`  | String | Required |    -    | User ID.    |

#### Basic usage [#basic-usage-35]

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

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

#### Return [#return-5]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `UnsubscribeUserMetadataResult` object, defined as follows:

```dart
  class UnsubscribeUserMetadataResult {
      final String userId; // The user ID of the current operation
  }
```

### MetadataItem [#metadataitem]

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

|   Properties   |  Type  | Required | Default | Description                                                                                                                                                                                                                                                                                       |
| :------------: | :----: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|      `key`     | String | Optional |    -    | Key.                                                                                                                                                                                                                                                                                              |
|     `value`    | String | Optional |    -    | Value.                                                                                                                                                                                                                                                                                            |
| `authorUserId` | String | Optional |    -    | The user ID of the editor. This value is read-only and does not support writing.                                                                                                                                                                                                                  |
|   `revision`   |   int  | Optional |   `-1`  | <br />- Returns the real version number in read operations.<br />- Serves as a version control switch in write operations:<br />- `-1`: Disable the version verification. <br />- > `0`: Enable version verification, only perform the operation if the target version number matches this value. |
|   `updateTs`   |   int  | Optional |   `0`   | Update timestamp. This value is read-only and does not support writing.                                                                                                                                                                                                                           |

## Lock [#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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    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.
  </CalloutDescription>
</CalloutContainer>

RtmLock
Lock instance

### setLock [#setlock]

#### Description [#description-37]

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](#event-listeners).

#### Method [#method-36]

You can call the `setLock` method as follows:

```dart
Future<(RtmStatus, SetLockResult?)> setLock(
    String channelName,
    RtmChannelType channelType,
    String lockName,
    {
        int? ttl = 10
    }
);
```

|   Parameters  |       Type       | Required | Default | Description                                                                                                                                                                                                                                                                                                                        |
| :-----------: | :--------------: | :------: | :-----: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `channelName` |      String      | Required |    -    | Channel name.                                                                                                                                                                                                                                                                                                                      |
| `channelType` | `RtmChannelType` | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                                                                                                                                                                                                                         |
|   `lockName`  |      String      | Required |    -    | Lock name.                                                                                                                                                                                                                                                                                                                         |
|     `ttl`     |        int       | Optional |    10   | The 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 [#basic-usage-36]

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

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

#### Return [#return-6]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `SetLockResult` object, defined as follows:

```dart
  class SetLockResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final String lockName; // Lock name
  }
```

### acquireLock [#acquirelock]

#### Description [#description-38]

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](#event-listeners).

#### Method [#method-37]

You can call the `acquireLock` method as follows:

```dart
Future<(RtmStatus, AcquireLockResult?)> acquireLock(
    String channelName,
    RtmChannelType channelType,
    String lockName,
    {
        bool retry = false
    }
);
```

|   Parameters  |       Type       | Required | Default | Description                                                                                                    |
| :-----------: | :--------------: | :------: | :-----: | :------------------------------------------------------------------------------------------------------------- |
| `channelName` |      String      | Required |    -    | Channel name.                                                                                                  |
| `channelType` | `RtmChannelType` | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                     |
|   `lockName`  |      String      | Required |    -    | Lock name.                                                                                                     |
|    `retry`    |       bool       | Optional |  false  | If the lock acquisition fails, whether to retry until the acquisition succeeds or the user leaves the channel. |

#### Basic usage [#basic-usage-37]

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

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

#### Return [#return-7]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns an `AcquireLockResult` object, defined as follows:

```dart
  class AcquireLockResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final String lockName; // Lock name
      final String errorDetails; // Error details
  }
```

### releaseLock [#releaselock-2]

#### Description [#description-39]

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](#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 [#method-38]

You can call the `releaseLock` method as follows:

```dart
Future<(RtmStatus, ReleaseLockResult?)> releaseLock(
    String channelName,
    RtmChannelType channelType,
    String lockName
);
```

|   Parameters  |       Type       | Required | Default | Description                                                |
| :-----------: | :--------------: | :------: | :-----: | :--------------------------------------------------------- |
| `channelName` |      String      | Required |    -    | Channel name.                                              |
| `channelType` | `RtmChannelType` | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e). |
|   `lockName`  |      String      | Required |    -    | Lock name.                                                 |

#### Basic usage [#basic-usage-38]

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

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

#### Return [#return-8]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `ReleaseLockResult` object, defined as follows:

```dart
  class ReleaseLockResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final String lockName; // Lock name
  }
```

### revokeLock [#revokelock]

#### Description [#description-40]

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](#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 [#method-39]

You can call the `revokeLock` method as follows:

```dart
Future<(RtmStatus, RevokeLockResult?)> revokeLock(
    String channelName,
    RtmChannelType channelType,
    String lockName,
    String owner
);
```

|   Parameters  |       Type       | Required | Default | Description                                                |
| :-----------: | :--------------: | :------: | :-----: | :--------------------------------------------------------- |
| `channelName` |      String      | Required |    -    | Channel name.                                              |
| `channelType` | `RtmChannelType` | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e). |
|   `lockName`  |      String      | Required |    -    | Lock name.                                                 |
|    `owner`    |      String      | Required |    -    | The ID of the user who has a lock.                         |

#### Basic usage [#basic-usage-39]

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

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

#### Return [#return-9]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `RevokeLockResult` object, defined as follows:

```dart
  class RevokeLockResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final String lockName; // Lock name
  }
```

###

#### Description [#description-41]

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 [#method-40]

You can call the \`\` method as follows:

```dart
Future<(RtmStatus, GetLocksResult?)> getLocks(
    String channelName,
    RtmChannelType channelType
);
```

|   Parameters  |       Type       | Required | Default | Description                                                |
| :-----------: | :--------------: | :------: | :-----: | :--------------------------------------------------------- |
| `channelName` |      String      | Required |    -    | Channel name.                                              |
| `channelType` | `RtmChannelType` | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e). |

#### Basic usage [#basic-usage-40]

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

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

#### Return [#return-10]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `GetLocksResult` object, defined as follows:

```dart
  class GetLocksResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final List<LockDetail> lockDetailList; // Lock details
      final int count; // Lock count
  }
```

### removeLock [#removelock]

#### Description [#description-42]

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](#event-listeners).

#### Method [#method-41]

You can call the `removeLock` method as follows:

```dart
Future<(RtmStatus, RemoveLockResult?)> removeLock(
    String channelName,
    RtmChannelType channelType,
    String lockName
);
```

|   Parameters  |       Type       | Required | Default | Description                                                |
| :-----------: | :--------------: | :------: | :-----: | :--------------------------------------------------------- |
| `channelName` |      String      | Required |    -    | Channel name.                                              |
| `channelType` | `RtmChannelType` | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e). |
|   `lockName`  |      String      | Required |    -    | Lock name.                                                 |

#### Basic usage [#basic-usage-41]

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

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

#### Return [#return-11]

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:

```dart
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).

* If the method call succeeds, the second item of the tuple returns a `RemoveLockResult` object, defined as follows:

```dart
  class RemoveLockResult {
      final String channelName; // Channel name
      final RtmChannelType channelType; // Channel type
      final String lockName; // Lock name
  }
```

## Enumerated types [#enumerated-types]

### Enum [#enum]

#### RtmAreaCode [#rtmareacode]

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

|  Value | Description                                   |
| :----: | --------------------------------------------- |
|  `cn`  | `0x00000001`: Mainland China.                 |
|  `na`  | `0x00000002`: North America.                  |
|  `eu`  | `0x00000004`: Europe.                         |
|  `asm` | `0x00000008`: Asia, excluding Mainland China. |
|  `jp`  | `0x00000010`: Japan.                          |
|  `ind` | `0x00000020`: India.                          |
| `glob` | `0xFFFFFFFF`: Global.                         |

#### RtmChannelType [#rtmchanneltype]

Channel types.

|   Value   | Description           |
| :-------: | --------------------- |
| `message` | `1`: Message channel. |
|  `stream` | `2`: Stream channel.  |
|   `user`  | `3`: User Channel.    |

#### RtmConnectionChangeReason [#rtmconnectionchangereason]

Reasons causing the change of the connection state.

|              Value             | Description                                                                                                                                                               |
| :----------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|          `connecting`          | `0`: The SDK is connecting with the server.                                                                                                                               |
|          `joinSuccess`         | `1`: The SDK has joined the channel successfully.                                                                                                                         |
|          `interrupted`         | `2`: The connection between the SDK and the server is interrupted.                                                                                                        |
|        `bannedByServer`        | `3`: The connection between the SDK and the server is banned by the server.                                                                                               |
|          `joinFailed`          | `4`: 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. |
|         `leaveChannel`         | `5`: The SDK has left the channel.                                                                                                                                        |
|         `invalidAppId`         | `6`: The connection failed because the App ID is not valid.                                                                                                               |
|      `invalidChannelName`      | `7`: The connection failed because the channel name is not valid.                                                                                                         |
|         `invalidToken`         | `8`: The connection failed because the token is not valid.                                                                                                                |
|         `tokenExpired`         | `9`: The connection failed because the token is expired.                                                                                                                  |
|       `rejectedByServer`       | `10`: The connection is rejected by server.                                                                                                                               |
|      `settingProxyServer`      | `11`: The connection state changed to reconnecting because the SDK has set a proxy server.                                                                                |
|          `renewToken`          | `12`: The connection state changed because the token is renewed.                                                                                                          |
|    `clientIpAddressChanged`    | `13`: The IP address of the client has changed, possibly because the network type, IP address, or port has been changed.                                                  |
|       `keepAliveTimeout`       | `14`: Timeout for the keep-alive of the connection between the SDK and the server. The connection state changes to reconnecting.                                          |
|         `rejoinSuccess`        | `15`: The user has rejoined the channel successfully.                                                                                                                     |
|             `lost`             | `16`: The connection between the SDK and the server is lost.                                                                                                              |
|           `echoTest`           | `17`: The connection state changes due to the echo test.                                                                                                                  |
| `clientIpAddressChangedByUser` | `18`: The local IP address was changed by the user. The connection state changes to reconnecting.                                                                         |
|         `sameUidLogin`         | `19`: The user joined the same channel from different devices with the same UID.                                                                                          |
|      `tooManyBroadcasters`     | `20`: The number of hosts in the channel has reached the upper limit.                                                                                                     |
|   `licenseValidationFailure`   | `21`: The license validation failed.                                                                                                                                      |
|  `certificationVerifyFailure`  | `22`: The server certificate validation failed.                                                                                                                           |
|   `streamChannelNotAvailable`  | `23`: The stream channel does not exist.                                                                                                                                  |
|       `inconsistentAppid`      | `24`: The App ID does not match the token.                                                                                                                                |
|         `loginSuccess`         | `10001`: The SDK logs in to the Signaling system.                                                                                                                         |
|            `logout`            | `10002`: The SDK logs out from the Signaling system.                                                                                                                      |
|       `presenceNotReady`       | `10003`: 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 [#rtmconnectionstate]

SDK connection states.

|      Value     | Description                                                           |
| :------------: | --------------------------------------------------------------------- |
| `disconnected` | `1`: The SDK has disconnected with the server.                        |
|  `connecting`  | `2`: The SDK is connecting with the server.                           |
|   `connected`  | `3`: The SDK has connected with the server.                           |
| `reconnecting` | `4`: The connection is lost. The SDK is reconnecting with the server. |
|    `failed`    | `5`: The SDK failed to connect with the server.                       |

#### RtmLinkStateChangeReason [#rtmlinkstatechangereason]

| Value                             | Description                                  |
| --------------------------------- | -------------------------------------------- |
| `unknown`                         | `0`: Unknown reason.                         |
| `login`                           | `1`: Logging in.                             |
| `loginSuccess`                    | `2`: Login successful.                       |
| `loginTimeout`                    | `3`: Login timeout.                          |
| `loginNotAuthorized`              | `4`: Login not authorized.                   |
| `loginRejected`                   | `5`: Login rejected.                         |
| `relogin`                         | `6`: Re-login.                               |
| `logout`                          | `7`: Logout.                                 |
| `autoReconnect`                   | `8`: Auto-reconnect.                         |
| `reconnectTimeout`                | `9`: Reconnect timeout.                      |
| `reconnectSuccess`                | `10`: Reconnect successful.                  |
| `join`                            | `11`: Joining a channel.                     |
| `joinSuccess`                     | `12`: Join channel successful.               |
| `joinFailed`                      | `13`: Join channel failed.                   |
| `rejoin`                          | `14`: Re-join a channel.                     |
| `leave`                           | `15`: Leave a channel.                       |
| `invalidToken`                    | `16`: Invalid token.                         |
| `tokenExpired`                    | `17`: Token expired.                         |
| `inconsistentAppId`               | `18`: Inconsistent app ID.                   |
| `invalidChannelName`              | `19`: Invalid channel name.                  |
| `invalidUserId`                   | `20`: Invalid user ID.                       |
| `notInitialized`                  | `21`: SDK not initialized.                   |
| `rtmServiceNotConnected`          | `22`: RTM service not connected.             |
| `channelInstanceExceedLimitation` | `23`: Channel instance exceeds the limit.    |
| `operationRateExceedLimitation`   | `24`: Operation frequency exceeds the limit. |
| `channelInErrorState`             | `25`: Channel in error state.                |
| `presenceNotConnected`            | `26`: Presence service not connected.        |
| `sameUidLogin`                    | `27`: Login with the same user ID.           |
| `kickedOutByServer`               | `28`: Kicked out by the server.              |
| `keepAliveTimeout`                | `29`: Keepalive timeout.                     |
| `connectionError`                 | `30`: Connection error.                      |
| `presenceNotReady`                | `31`: Presence service not ready.            |
| `networkChange`                   | `32`: Network changed.                       |
| `serviceNotSupported`             | `33`: Service not supported.                 |
| `streamChannelNotAvailable`       | `34`: Stream Channel not available.          |
| `storageNotAvailable`             | `35`: Storage service not available.         |
| `lockNotAvailable`                | `36`: Lock service not available.            |
| `loginTooFrequent`                | `37`: The login operation is too frequent.   |

#### RtmEncryptionMode [#rtmencryptionmode]

Encryption mode.

|    Value    | Description            |
| :---------: | ---------------------- |
|    `none`   | `0`: No encryption.    |
| `aes128Gcm` | `1`: AES-128-GCM mode. |
| `aes256Gcm` | `2`: AES-256-GCM mode. |

#### RtmLockEventType [#rtmlockeventtype]

Lock event type.

|      Value     | Description                                                     |
| :------------: | --------------------------------------------------------------- |
|   `snapshot`   | `1`: The snapshot of the lock when the user joined the channel. |
|    `lockSet`   | `2`: The lock is set.                                           |
|  `lockRemoved` | `3`: The lock is removed.                                       |
| `lockAcquired` | `4`: The lock is acquired.                                      |
| `lockReleased` | `5`: The lock is released.                                      |
|  `lockExpired` | `6`: The lock expired.                                          |

#### RtmLogLevel [#rtmloglevel]

Log output levels.

|  Value  | Description                                                                                                    |
| :-----: | -------------------------------------------------------------------------------------------------------------- |
|  `none` | `0x0000`: No log.                                                                                              |
|  `info` | `0x0001`: Output the log at the `FATAL`, `ERROR`, `WARN`, or `INFO` level. We recommend you set to this value. |
|  `warn` | `0x0002`: Output the log at the `FATAL`, `ERROR`, `WARN` level.                                                |
| `error` | `0x0004`: Output the log at the `FATAL`, `ERROR` level.                                                        |
| `fatal` | `0x0008`: Output the log at the `FATAL` level.                                                                 |

#### RtmMessagePriority [#rtmmessagepriority]

Message priority.

|   Value   | Description   |
| :-------: | ------------- |
| `highest` | `0`: Highest. |
|   `high`  | `1`: High.    |
|  `normal` | `4`: Normal.  |
|   `low`   | `8`: Low.     |

#### RtmMessageQos [#rtmmessageqos]

QoS guarantee when sending topic messages.

|    Value    | Description                                             |
| :---------: | ------------------------------------------------------- |
| `unordered` | `0`: Message data is not guaranteed to arrive in order. |
|  `ordered`  | `1`: Message data arrives in order.                     |

#### RtmMessageType [#rtmmessagetype]

Message Type.

| Enum Value | Description       |
| :--------: | ----------------- |
|  `binary`  | `0`: Binary type. |
|  `string`  | `1`: String type. |

#### RtmPresenceEventType [#rtmpresenceeventtype]

Presence event type.

|         Value        | Description                                                                                                                     |
| :------------------: | ------------------------------------------------------------------------------------------------------------------------------- |
|      `snapshot`      | `1`: The snapshot of the presence when the user joined the channel.                                                             |
|      `interval`      | `2`: When users in the channel reach the setting value, the event notifications are sent at intervals rather than in real time. |
|  `remoteJoinChannel` | `3`: A remote user joined the channel.                                                                                          |
| `remoteLeaveChannel` | `4`: A remote user left the channel.                                                                                            |
|    `remoteTimeout`   | `5`: A remote user's connection timed out.                                                                                      |
| `remoteStateChanged` | `6`: A remote user's temporary state changed.                                                                                   |
|  `errorOutOfService` | `7`: The user did not enable presence when joining the channel.                                                                 |

#### RtmLinkOperation [#rtmlinkoperation]

Operation type.

|      Value      | Description                                                                                          |
| :-------------: | ---------------------------------------------------------------------------------------------------- |
|     `login`     | `0`: The user logins to the Signaling system.                                                        |
|     `logout`    | `1`: The user logouts of the Signaling system.                                                       |
|      `join`     | `2`: The user joins in a stream channel.                                                             |
|     `leave`     | `3`: The user leaves a stream channel.                                                               |
|  `serverReject` | `4`: The Signaling server reject the connection.                                                     |
| `autoReconnect` | `5`: The SDK is automatically reconnecting to the Signaling server.                                  |
|  `reconnected`  | `6`: The SDK is reconnected to the Signaling server.                                                 |
| `heartbeatLost` | `7`: The Signaling server does not receive the heartbeat packet within the specified timeout period. |
| `serverTimeout` | `8`: The Signaling server has timed out.                                                             |
| `networkChange` | `9`: The network status changes.                                                                     |

#### RtmLinkState [#rtmlinkstate]

Link state type.

|      Value     | Description          |
| :------------: | -------------------- |
|     `idle`     | `0`: The init state. |
|  `connecting`  | `1`: Connecting.     |
|   `connected`  | `2`: Connected.      |
| `disconnected` | `3`: Disconnected.   |
|   `suspended`  | `4`: Suspended.      |
|    `failed`    | `5`: Failed.         |

#### RtmProtocolType [#rtmprotocoltype]

Protocol type.

|   Value   | Description                      |
| :-------: | -------------------------------- |
|  `tcpUdp` | `0`: Both TCP and UDP protocols. |
| `tcpOnly` | `1`: Only TCP protocol.          |

#### RtmServiceType [#rtmservicetype]

Service type

|   Value   | Description                                                                                                 |
| :-------: | ----------------------------------------------------------------------------------------------------------- |
| `message` | The foundational services comprise the message channel, user channel, presence, storage, and lock services. |
|  `stream` | The stream channel service.                                                                                 |

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

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

#### RtmProxyType [#rtmproxytype]

Proxy type.

|    Value   | Description                                       |
| :--------: | ------------------------------------------------- |
|   `none`   | `0`: Do not enable the proxy.                     |
|   `http`   | `1`: Enable the proxy for the HTTP protocol.      |
| `cloudTcp` | `2`: Enable the cloud proxy for the TCP protocol. |

#### RtmStorageEventType [#rtmstorageeventtype]

Storage event type.

|    Value   | Description                                                                                                                                                          |
| :--------: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `snapshot` | `1`: 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. |
|    `set`   | `2`: Occurs when calling `setChannelMetadata` or `setUserMetadata`. Caution: This event only occurs in incremental data update mode.                                 |
|  `update`  | `3`: Occurs when calling methods to set, update, or delete the channel metadata or user metadata.                                                                    |
|  `remove`  | `4`: Occurs when calling `removeChannelMetadata` or `removeUserMetadata`. Caution: This event only occurs in incremental data update mode.                           |

#### RtmStorageType [#rtmstoragetype]

Storage type.

|   Value   | Description                  |
| :-------: | ---------------------------- |
|   `user`  | `1`: User metadata event.    |
| `channel` | `2`: Channel metadata event. |

#### RtmTopicEventType [#rtmtopiceventtype]

Topic event type.

|        Value       | Description                                                      |
| :----------------: | ---------------------------------------------------------------- |
|     `snapshot`     | `1`: The snapshot of the topic when the user joined the channel. |
|  `remoteJoinTopic` | `2`: A remote user joined the channel.                           |
| `remoteLeaveTopic` | `3`: A remote user left the channel.                             |

## Troubleshooting [#troubleshooting]

Refer to the following information for troubleshooting API calls.

### ErrorInfo [#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:

```dart
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).

### Error codes table [#error-codes-table]

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

| Error code | Error description                      | Cause and solution                                                                                                                                                                                                                                                                                                                                   |
| :--------- | :------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `0`        | `ok`                                   | Correct call                                                                                                                                                                                                                                                                                                                                         |
| `-10001`   | `notInitialized`                       | The SDK is not initialized. Please initialize the `RtmClient` instance by calling the `createAgoraRtmClient` method before performing other operations.                                                                                                                                                                                              |
| `-10002`   | `notLogin`                             | The user called the API without logging in to Signaling, disconnected due to timeout, or actively logged out. Please log in to Signaling first.                                                                                                                                                                                                      |
| `-10003`   | `invalidAppId`                         | Invalid App ID: <br /> - Check that the App ID is correct. <br /> - Ensure that Signaling has been activated for the App ID.                                                                                                                                                                                                                         |
| `-10005`   | `invalidToken`                         | Invalid Token: <br /> - The token is invalid, check whether the Token Provider generates a valid Signaling Token.                                                                                                                                                                                                                                    |
| `-10006`   | `invalidUserId`                        | Invalid User ID: <br /> - Check if user ID is empty. <br /> - Check if the user ID contains illegal characters.                                                                                                                                                                                                                                      |
| `-10007`   | `initServiceFailed`                    | SDK initialization failed. Please reinitialize by calling the `createAgoraRtmClient` method.                                                                                                                                                                                                                                                         |
| `-10008`   | `invalidChannelName`                   | Invalid channel name: <br /> - Check if the channel name is empty. <br /> - Check if the channel name contains illegal characters.                                                                                                                                                                                                                   |
| `-10009`   | `tokenExpired`                         | Token expired. Call `renewToken` to reacquire the Token.                                                                                                                                                                                                                                                                                             |
| `-10010`   | `loginNoServerResources`               | Server resources are limited. It is recommended to log in again.                                                                                                                                                                                                                                                                                     |
| `-10011`   | `loginTimeout`                         | Login timeout. Check whether the current network is stable and switch to a stable network environment.                                                                                                                                                                                                                                               |
| `-10012`   | `loginRejected`                        | SDK login rejected by the server: <br /> - Check tha Signaling is activated on your App ID. <br /> - Check if the token or `userId` is banned.                                                                                                                                                                                                       |
| `-10013`   | `loginAborted`                         | SDK login interrupted due to unknown problem: <br /> - Check that the current network is stable and switch to a stable network environment. <br /> - The current `userId` is logged in.                                                                                                                                                              |
| `-10014`   | `invalidParameter`                     | Invalid parameter. Please check if the parameters you provided are correct.                                                                                                                                                                                                                                                                          |
| `-10015`   | `loginNotAuthorized`                   | No RTM service permissions. Check that the console opens Signaling services.                                                                                                                                                                                                                                                                         |
| `-10016`   | `inconsistentAppid`                    | Inconsistent App ID. Please check whether the App ID used for initialization, login, and joining a channel are consistent.                                                                                                                                                                                                                           |
| `-10017`   | `duplicateOperation`                   | Duplicate operation.                                                                                                                                                                                                                                                                                                                                 |
| `-10018`   | `instanceAlreadyReleased`              | Repeat `rtm` instantiation or `RTMStreamChannel` instantiation.                                                                                                                                                                                                                                                                                      |
| `-10019`   | `invalidChannelType`                   | Invalid channel type. The SDK only supports the following channel types. Please use the correct value: <br /> - `message`: Message Channel <br /> - `stream`: Stream Channel <br /> - `user`: User Channel                                                                                                                                           |
| `-10020`   | `invalidEncryptionParameter`           | Message encryption parameters are invalid. <br />- Check that the encryption key generated is a String. <br />- Check that the generated encryption salt is `Uint8Array` type and that the length is 32 bytes. <br />- Check that the encryption method matches the encryption key and the encryption salt.                                          |
| `-10021`   | `operationRateExceedLimitation`        | Channel metadata or User Metadata -related API call frequency is exceeding the limit. Please control the call frequency within 10/second.                                                                                                                                                                                                            |
| `-10022`   | `serviceNotSupported`                  | The 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.                                                                                                                                                                     |
| `-10023`   | `loginCanceled`                        | The login operation has been canceled. Possible reasons are as follows: <br />- 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. <br />- Calling the `logout` method to log out before successfully logging in. |
| `-10024`   | `invalidPrivateConfig`                 | The private deployment parameter settings are invalid. Please check whether the service type and server address you set in `RtmPrivateConfig` are valid.                                                                                                                                                                                             |
| `-10025`   | `notConnected`                         | Not connected to the Signaling server.                                                                                                                                                                                                                                                                                                               |
| `-10026`   | `renewTokenTimeout`                    | Token renewal timed out.                                                                                                                                                                                                                                                                                                                             |
| `-11001`   | `channelNotJoined`                     | The user has not joined the channel: <br /> - The user is not online, offline or has not joined the channel<br /> - Check for typos in `userId`.                                                                                                                                                                                                     |
| `-11002`   | `channelNotSubscribed`                 | The user has not subscribed to the channel: <br /> - The user is not online, offline or has not joined the channel<br /> - Check for typos in `userId`.                                                                                                                                                                                              |
| `-11003`   | `channelExceedTopicUserLimitation`     | The number of subscribers to this topic exceeds the limit.                                                                                                                                                                                                                                                                                           |
| `-11004`   | `channelInReuse`                       | In co-channel mode, RTM released the Stream Channel.                                                                                                                                                                                                                                                                                                 |
| `-11005`   | `channelInstanceExceedLimitation`      | The number of created or subscribed channels exceeds the limit. See [API usage limits](/en/realtime-media/rtm/reference/limitations) for details.                                                                                                                                                                                                    |
| `-11006`   | `channelInErrorState`                  | Channel is not available. Please recreate the Stream Channel or resubscribe to the Message Channel.                                                                                                                                                                                                                                                  |
| `-11007`   | `channelJoinFailed`                    | Failed to join this channel: <br /> - Check if the number of joined channels exceeds the limit. <br /> - Check if the channel name is illegal. <br /> - Check if the network is disconnected.                                                                                                                                                        |
| `-11008`   | `channelInvalidTopicName`              | Invalid topic name: <br /> - Check whether the topic name contains illegal characters. <br /> - Check if the topic name is empty.                                                                                                                                                                                                                    |
| `-11009`   | `channelInvalidMessage`                | Invalid message. Check whether the message type is legal, Signaling only supports `string`, `Uint8Array` type messages.                                                                                                                                                                                                                              |
| `-11010`   | `channelMessageLengthExceedLimitation` | Message length exceeded limit. Check if the message payload size exceeds the limit: <br /> - Message Channel single message package limit is 32 KB. <br /> - Stream Channel single message package limit is 1 KB.                                                                                                                                    |
| `-11011`   | `channelInvalidUserList`               | Invalid user list: <br /> - Check if the user list is empty. <br /> - Check if the user list contains invalid entries.                                                                                                                                                                                                                               |
| `-11012`   | `channelNotAvailable`                  | Invalid user list: <br /> - Check if the user list is empty<br /> - Check if the user list contains illegal items.                                                                                                                                                                                                                                   |
| `-11013`   | `channelTopicNotSubscribed`            | The topic is not subscribed.                                                                                                                                                                                                                                                                                                                         |
| `-11014`   | `channelExceedTopicLimitation`         | The number of topics exceeds the limit.                                                                                                                                                                                                                                                                                                              |
| `-11015`   | `channelJoinTopicFailed`               | Failed to join this topic. Check whether the number of added topics exceeds the limit.                                                                                                                                                                                                                                                               |
| `-11016`   | `channelTopicNotJoined`                | The topic has not been joined. To send a message, you need to join the Topic first.                                                                                                                                                                                                                                                                  |
| `-11017`   | `channelTopicNotExist`                 | The topic does not exist. Check that the topic name is correct.                                                                                                                                                                                                                                                                                      |
| `-11018`   | `channelInvalidTopicMeta`              | The `meta` parameters in the topic are invalid. Check if the `meta` parameter exceeds 256 bytes.                                                                                                                                                                                                                                                     |
| `-11019`   | `channelSubscribeTimeout`              | Channel subscription timed out. Check for broken connections.                                                                                                                                                                                                                                                                                        |
| `-11020`   | `channelSubscribeTooFrequent`          | The 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.                                                                                                                                                                            |
| `-11021`   | `channelSubscribeFailed`               | Channel subscription failed. Check if the number of subscribed channels exceeds the limit.                                                                                                                                                                                                                                                           |
| `-11022`   | `channelUnsubscribeFailed`             | Failed to unsubscribe from the channel. Check if the connection is disconnected.                                                                                                                                                                                                                                                                     |
| `-11023`   | `channelEncryptMessageFailed`          | Message encryption failed: <br /> - Check that the `cipherKey` is valid. <br /> - Check that the `salt` is valid. <br /> - Check if `encryptionMode` mode matches the `cipherKey` and `salt`.                                                                                                                                                        |
| `-11024`   | `channelPublishMessageFailed`          | Message publishing failed. Check for broken connections.                                                                                                                                                                                                                                                                                             |
| `-11026`   | `channelPublishMessageTimeout`         | Message publishing timed out. Check for broken connections.                                                                                                                                                                                                                                                                                          |
| `-11027`   | `channelNotConnected`                  | The SDK is disconnected from the Signaling server. Please log in again.                                                                                                                                                                                                                                                                              |
| `-11028`   | `channelLeaveFailed`                   | Failed to leave the channel. Check for broken connections.                                                                                                                                                                                                                                                                                           |
| `-11029`   | `channelCustomTypeLengthOverflow`      | Custom type length overflow. The length of the `customType` field must to be within 32 characters.                                                                                                                                                                                                                                                   |
| `-11030`   | `channelInvalidCustomType`             | `customType` field is invalid. Check the `customType` field for illegal characters.                                                                                                                                                                                                                                                                  |
| `-11031`   | `channelUnsupportedMessageType`        | Message type is not supported.                                                                                                                                                                                                                                                                                                                       |
| `-11032`   | `channelPresenceNotReady`              | Presence service is not ready. Please rejoin the Stream Channel or resubscribe to the Message Channel.                                                                                                                                                                                                                                               |
| `-11033`   | `channelReceiverOffline`               | When sending a user message, the remote user is offline: <br /> - Check if the user ID set when calling the method is correct.<br /> - Check if the remote user is logged in and online.                                                                                                                                                             |
| `-11034`   | `channelJoinCanceled`                  | The 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.                                                                                                              |
| `-12001`   | `storageOperationFailed`               | Storage operation failed.                                                                                                                                                                                                                                                                                                                            |
| `-12002`   | `storageMetadataItemExceedLimitation`  | The number of Storage Metadata Items exceeds the limit.                                                                                                                                                                                                                                                                                              |
| `-12003`   | `storageInvalidMetadataItem`           | Invalid Metadata Item.                                                                                                                                                                                                                                                                                                                               |
| `-12004`   | `storageInvalidArgument`               | Invalid argument.                                                                                                                                                                                                                                                                                                                                    |
| `-12005`   | `storageInvalidRevision`               | Invalid Revision parameter.                                                                                                                                                                                                                                                                                                                          |
| `-12006`   | `storageMetadataLengthOverflow`        | Metadata overflows.                                                                                                                                                                                                                                                                                                                                  |
| `-12007`   | `storageInvalidLockName`               | Invalid Lock name.                                                                                                                                                                                                                                                                                                                                   |
| `-12008`   | `storageLockNotAcquired`               | The Lock was not acquired.                                                                                                                                                                                                                                                                                                                           |
| `-12009`   | `storageInvalidKey`                    | Invalid Metadata key.                                                                                                                                                                                                                                                                                                                                |
| `-12010`   | `storageInvalidValue`                  | Invalid metadata value.                                                                                                                                                                                                                                                                                                                              |
| `-12011`   | `storageKeyLengthOverflow`             | Metadata key length overflow.                                                                                                                                                                                                                                                                                                                        |
| `-12012`   | `storageValueLengthOverflow`           | Metadata value length overflow.                                                                                                                                                                                                                                                                                                                      |
| `-12013`   | `storageDuplicateKey`                  | Duplicate Metadata Item key.                                                                                                                                                                                                                                                                                                                         |
| `-12014`   | `storageOutdatedRevision`              | Outdated Revision parameter.                                                                                                                                                                                                                                                                                                                         |
| `-12015`   | `storageNotSubscribe`                  | This channel is not subscribed.                                                                                                                                                                                                                                                                                                                      |
| `-12016`   | `storageInvalidMetadataInstance`       | Metadata instance does not exist. Please create a Metadata instance.                                                                                                                                                                                                                                                                                 |
| `-12017`   | `storageSubscribeUserExceedLimitation` | The number of subscribers exceeds the limit.                                                                                                                                                                                                                                                                                                         |
| `-12018`   | `storageOperationTimeout`              | Storage operation timed out.                                                                                                                                                                                                                                                                                                                         |
| `-12019`   | `storageNotAvailable`                  | The Storage service is not available.                                                                                                                                                                                                                                                                                                                |
| `-13001`   | `presenceNotConnected`                 | The user is not connected to the system.                                                                                                                                                                                                                                                                                                             |
| `-13002`   | `presenceNotWritable`                  | Presence service is unavailable.                                                                                                                                                                                                                                                                                                                     |
| `-13003`   | `presenceInvalidArgument`              | Invalid argument.                                                                                                                                                                                                                                                                                                                                    |
| `-13004`   | `presenceCachedTooManyStates`          | The temporary user state cached before joining the channel exceeds the limit. See [API usage limits](/en/realtime-media/rtm/reference/limitations) for details.                                                                                                                                                                                      |
| `-13005`   | `presenceStateCountOverflow`           | The number of temporary user state key/value pairs exceeds the limit. See [API usage limits](/en/realtime-media/rtm/reference/limitations) for details.                                                                                                                                                                                              |
| `-13006`   | `presenceInvalidStateKey`              | Invalid state key.                                                                                                                                                                                                                                                                                                                                   |
| `-13007`   | `presenceInvalidStateValue`            | Invalid state value.                                                                                                                                                                                                                                                                                                                                 |
| `-13008`   | `presenceStateKeySizeOverflow`         | Presence key length overflow.                                                                                                                                                                                                                                                                                                                        |
| `-13009`   | `presenceStateValueSizeOverflow`       | Presence value overflow                                                                                                                                                                                                                                                                                                                              |
| `-13010`   | `presenceStateDuplicateKey`            | Repeated state key.                                                                                                                                                                                                                                                                                                                                  |
| `-13011`   | `presenceUserNotExist`                 | The user does not exist.                                                                                                                                                                                                                                                                                                                             |
| `-13012`   | `presenceOperationTimeout`             | Presence operation timed out.                                                                                                                                                                                                                                                                                                                        |
| `-13013`   | `presenceOperationFailed`              | Presence operation failed.                                                                                                                                                                                                                                                                                                                           |
| `-14001`   | `lockOperationFailed`                  | Lock operation failed.                                                                                                                                                                                                                                                                                                                               |
| `-14002`   | `lockOperationTimeout`                 | Lock operation timed out.                                                                                                                                                                                                                                                                                                                            |
| `-14003`   | `lockOperationPerforming`              | Lock operation in progress.                                                                                                                                                                                                                                                                                                                          |
| `-14004`   | `lockAlreadyExist`                     | Lock already exists.                                                                                                                                                                                                                                                                                                                                 |
| `-14005`   | `lockInvalidName`                      | Invalid Lock name.                                                                                                                                                                                                                                                                                                                                   |
| `-14006`   | `lockNotAcquired`                      | The Lock was not acquired.                                                                                                                                                                                                                                                                                                                           |
| `-14007`   | `lockAcquireFailed`                    | Failed to acquire the Lock.                                                                                                                                                                                                                                                                                                                          |
| `-14008`   | `lockNotExist`                         | The Lock does not exist.                                                                                                                                                                                                                                                                                                                             |
| `-14009`   | `lockNotAvailable`                     | Lock service is not available.                                                                                                                                                                                                                                                                                                                       |
