Allow your users to retrieve and manage messages within their postbox.
The message retrieval and management APIs allow users to access messages which have been sent to their postbox. Generally users will retrieve messages as soon after delivery as possible, and delete each message from the postbox once it has been handled.
Retrieving Relay Messages
Messages delivered to the user's postboxes can be retrieved using the single listMessages function. Messages are retrieved in order from oldest to newest.
Since the number of messages may be large, this function allows pagination of the returned results. The caller may optionally specify the maximum number of messages to return in a single iteration. If more are available than fit in that limit, then the returned construct will include a token which can be supplied to a subsequent iteration to fetch the next page.
If no limit is supplied, only a single message will be returned.
var allMessages: [Message] = []do {var messageResult =tryawait relayClient.listMessages(limit:nil, nextToken:nil) allMessages.append(contentsOf: messages.items)// If you wish to handle all retrievals in a single task contextwhile messageResult.nextToken !=nil { messageResult =tryawait relayClient.listMessages(limit:nil, nextToken: messageResult.nextToken) allMessages.append(contentsOf: messageResult.items) }} catch {// Handle errors}
var allMessages =mutableListOf<Message>()launch {try {var messagesList: OutputList<Message> =withContext(Dispatchers.IO) { relayClient.listMessages() } allMessages.addAll(messagesList.items)// If you wish to handle all retrievals in a single task contextwhile(messagesList.nextToken !=null) { messagesList =withContext(Dispatchers.IO) { relayClient.listMessages(null, messagesList.nextToken) } allMessages.addAll(messagesList.items) } } catch (e: SudoDIRelayClient.DIRelayException) {// Handle/notify user of exception }}
Deleting a Relay Message
A message can be deleted by using the deleteMessage function.
The deletion call will return the identifier of the deleted message on success, or throw an error upon failure.
// messageId: returned in the result of the listMessages calldo {_=tryawait relayClient.deleteMessage(withMessageId: messageId)} catch {// Handle error}
// messageId: returned in the result of the listMessages calllaunch {try {withContext(Dispatchers.IO) { relayClient.deleteMessage(messageId) } } catch (e: SudoDIRelayClient.DIRelayException) {// Handle/notify user of exception }}
Bulk Deleting Relay Messages
Up to 25 messages can be deleted with a single call to the bulkDeleteMessage function.
This call will return the identifiers of the deleted messages on success, or throw an error upon failure to delete any message.
// messageIds: returned in the result of the listMessages calldo {_=tryawait relayClient.bulkDeleteMessage(withMessageIds: messageIds)} catch {// Handle error}
// messageIds: returned in the result of the listMessages calllaunch {try {withContext(Dispatchers.IO) { relayClient.bulkDeleteMessage(messageIds) } } catch (e: SudoDIRelayClient.DIRelayException) {// Handle/notify user of exception }}
Subscribing to Incoming Relay Messages
Real-time data notification is supported in the Relay SDK. Calling the subscription method in the SDK ensures that data relating to relay messages will be posted to the client as they are received in the relay, as long as the client is connected.
Subscribing to Relay messages is done on a per-user basis, so all messages for all postboxes for the user will be delivered to the same notification method. Clients are able to demultiplex received messages using the postbox identifier or the owning Sudo identifier of the message.
Subscriptions are only active when the application is active. If the user navigates away from the application, the subscription will be closed, and the SDK notified, and the client must reconnect when the application is reactivated.
It is important to use subscriptions sparingly as they are resource intensive. It is recommended to only use them when a specific view is open. For example, it would be appropriate for the application to subscribe when a view of a list of relay messages is in the foreground. When the user navigates from this view, the application should cancel the subscription.
To subscribe to Relay messages, the client should specify a message received handler and a connection status change handler to deal with subscription status changes to ensure it is aware when the subscription becomes active or inactive. If the connection status changes to disconnected, the client must manually resubscribe in order to continue to receive notifications of new messages.
The input to the status change handler is the following:
// A list to hold our notified messagesprivatevar messagesReceived: [Message] = []// If this token is cleaned up or goes out of scope then the subscription// will be terminatedprivatevar subscriptionToken: SubscriptionToken?do { subscriptionToken =tryawait self.relayClient.subscribeToMessageCreated( statusChangeHandler: { result inswitch result {case .connected:// handle any implementation required// for sucessful subscription connectionreturncase .disconnected, .error: subscriptionToken?.cancel() subscriptionToken =nildefault:// no action required } }, resultHandler: { result inswitch result {case .success(message): messagesReceived.addItem(message)default:return } })} catch {// Handle error}
Note that for the connection to remain open, a strong reference needs to be kept to the subscription token.
Unsubscribing from message received notifications
To cancel a subscription, cancel the subscription Token or call the unsubscribeAll method to cancel all subscriptions.
// Either subscriptionToken?.cancel()// or relayClient.unsubscribeAll()
This will ensure that the subscription is cancelled and system resources are freed.
To subscribe to incoming relay messages, use the subscribeToRelayEvents method. You must pass an identifier of the subscription and an instance of a class that implements the MessageSubscriber interface. This class will be notified of incoming messages and any changes in the status of the subscription. If the connection status changes to DISCONNECTED, the client must manually resubscribe in order to continue to receive notifications of new messages.
The valid set of subscription status values is:
enumclassConnectionState {/** * Connected and receiving updates. */ CONNECTED,/** * Disconnected and won't receive any updates. When disconnected all subscribers will be * unsubscribed so the consumer must re-subscribe. */ DISCONNECTED}
Subscribing to message received notifications
// A list of received messagesprivatevar relayMessagesReceived =mutableListOf<Message>()val subscriber =object : MessageSubscriber {overridefunmessageCreated(message: Message) {// Handle incoming message. relayMessagesReceived.add(message) }overridefunconnectionStatusChanged(state: Subscriber.ConnectionState) {// Handle changes in the state of the subscription connection }}launch {try {withContext(Dispatchers.IO) { relayClient.subscribeToRelayEvents("unique-subscription-id", subscriber ) } } catch (e: SudoDIRelayClient.DIRelayException) {// Handle/notify user of exception }}
There is also an extension function that allows you to pass lambdas instead of an object that implements the MessageSubscriber interface.
// A list of received messagesprivatevar relayMessagesReceived =mutableListOf<Message>()launch {try {withContext(Dispatchers.IO) { relayClient.subscribeToRelayEvents("unique-subscription-id", onConnectionChange = { state: Subscriber.ConnectionState ->// Handle changes in the state of the subscription connection. }, messageCreated = { message: Message -> // Handle incoming message. relayMessagesReceived.add(message) } ) } } catch (e: SudoDIRelayClient.DIRelayException) {// Handle/notify user of exception }}
Unsubscribing from message received notifications
To cancel a subscription, use the unsubscribeToRelayEvents or unsubscribeAll method.