Manage Relay Messages

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 = 
        try await relayClient.listMessages(limit: nil, nextToken: nil)
    allMessages.append(contentsOf: messages.items)
    // If you wish to handle all retrievals in a single task context
    while messageResult.nextToken != nil {
      messageResult = 
          try await relayClient.listMessages(limit: nil, nextToken: messageResult.nextToken)
      allMessages.append(contentsOf: messageResult.items)    
    }
} catch {
    // Handle errors
}

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 call
do {
    _ = try await relayClient.deleteMessage(withMessageId: messageId)
} catch {
    // Handle error
}

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 call
do {
    _ = try await relayClient.bulkDeleteMessage(withMessageIds: messageIds)
} catch {
    // Handle error
}

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:

public enum PlatformSubscriptionStatus: Equatable {
    case initialized
    case connecting
    case connected
    case disconnected
    case error(Error)
}

Subscribing to message received notifications

// A list to hold our notified messages
private var messagesReceived: [Message] = []
// If this token is cleaned up or goes out of scope then the subscription
// will be terminated
private var subscriptionToken: SubscriptionToken?

do {
    subscriptionToken = try await self.relayClient.subscribeToMessageCreated(
        statusChangeHandler: { result in
            switch result {
            case .connected:
                // handle any implementation required
                // for sucessful subscription connection
                return
            case .disconnected, .error:
                subscriptionToken?.cancel()
                subscriptionToken = nil
            default:
                // no action required
            }
        },
        resultHandler: { result in
            switch 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.

Last updated