On this page

Message Persistence API for Kotlin SDK

Breaking changes in v9.0.0

PubNub Kotlin SDK version 9.0.0 unifies the codebases for Kotlin and Java SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted status events. These changes can impact applications built with previous versions (< 9.0.0 ) of the Kotlin SDK.

For more details about what has changed, refer to Java/Kotlin SDK migration guide.

Message Persistence gives you real-time access to the history of messages published to PubNub. Each message is timestamped to the nearest 10 nanoseconds and stored across multiple availability zones in several geographic locations. You can encrypt stored messages with AES-256 so they are not readable on PubNub’s network. For details, see Message Persistence.

You control how long messages are stored through your account’s retention policy. Options include: 1 day, 7 days, 30 days, 3 months, 6 months, 1 year, or Unlimited.

You can retrieve the following:

  • Messages
  • Message reactions
  • Files (using the File Sharing API)
Request execution

Most PubNub Kotlin SDK method invocations return an Endpoint object, which allows you to decide whether to perform the operation synchronously or asynchronously.

You must invoke the .sync() or .async() method on the Endpoint to execute the request, or the operation will not be performed.

1val channel = pubnub.channel("channelName")
2
3channel.publish("This SDK rules!").async { result ->
4 result.onFailure { exception ->
5 // Handle error
6 }.onSuccess { value ->
7 // Handle successful method result
8 }
9}

Batch history

Requires Message Persistence

Enable Message Persistence for your key in the Admin Portal. See how to enable add-on features.

Fetch historical messages from multiple channels. Use includeMessageActions or includeActions to include message actions.

You can control how messages are returned and in what order.

  • If you specify only start, you receive messages older than that timetoken. start is the newer boundary of the query (exclusive).
  • If you specify only end, you receive messages newer than or equal to that timetoken. end is the older boundary of the query (inclusive).
  • If you specify both start and end, start must be a higher timetoken than end. Results contain messages between those timetokens, excluding the message at start and including the message at end.
How to use the start and end parameters

PubNub retrieves messages by searching backward through time (newest to oldest). Because of this, the parameter names are the reverse of their intuitive meaning:

  • start is the newer boundary (higher timetoken value) - search begins here, exclusive
  • end is the older boundary (lower timetoken value) - search stops here, inclusive

When you provide both parameters, start must be a higher timetoken than end.

9:00 AM10:00 AM11:00 AM11:59 AM

Results are always returned in oldest-first order.

You can receive up to 100 messages for a single channel. For multiple channels (up to 500), you can receive up to 25 messages per channel. If more messages match the time range, make iterative calls and adjust the start timetoken to page through the results.

Method(s)

Use the following method(s) in the Kotlin SDK:

1pubnub.fetchMessages(
2 channels: List<String>,
3 page: PNBoundedPage,
4 includeMeta: Boolean,
5 includeMessageAction: Boolean,
6 includeMessageType: Boolean,
7 includeCustomMessageType: Boolean,
8).async { result -> }
* required
ParameterDescription
channels *
Type: List<String>
Default:
n/a
Channels to return history messages from.
page
Type: PNBoundedPage
Default:
n/a
The paging object used for pagination. Set limit to specify the number of historical messages to return per channel.
If includeMessageActions is false, then 100 is the default (and maximum) value. Otherwise it's 25.
Set start to the newer boundary (exclusive) — retrieval begins here and moves backward in time.
Set end to the older boundary (inclusive) — retrieval stops here. start must be a higher timetoken than end when both are provided.
includeMeta
Type: Boolean
Default:
false
Whether to include the message metadata in the response.
includeMessageActions
Type: Boolean
Default:
false
Whether to retrieve history messages with message actions. If true, limited to one channel only.
includeMessageType
Type: Boolean
Default:
true
Whether to pass true to include message type. Default is true.
includeCustomMessageType
Type: Boolean
Default:
false
Whether to retrieve messages with the custom message type. See Retrieving Messages.

Sample code

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
1

Returns

The fetchMessages() operation returns a map of channels and List<PNFetchMessagesResult> and PNBoundedPage object.

MethodDescription
channels
Type: HashMap<String, List<PNFetchMessageItem>>
Map of channels and their respective lists of PNFetchMessageItem. See PNFetchMessageItem for more details.
page
Type: PNBoundedPage
If exists indicates that more data is available. It can be passed directly to another call of fetchMessages to retrieve this remaining data.

PNFetchMessageItem

MethodDescription
message
Type: JsonElement
Message
timetoken
Type: Long
Timetoken of the message. Always returned by default.
meta
Type: JsonElement?
Metadata of the message. Is null if not requested, otherwise an empty string if requested but no associated metadata.
actions
Type: Map<String, HashMap<String, List<Action>>>?
The message actions associated with the message. Is null if not requested. The key of the map is the action type. The value is another map, which key is the actual value of the message action, and the key being a list of actions, ie. a list of UUIDs which have posted such a message action. See Action for more details.
customMessageType
Type: String
The custom message type.

Action

MethodDescription
uuid
Type: String
The UUID of the publisher.
actionTimetoken
Type: String
The publish timetoken of the action.

Other examples

Paging history responses

1

Delete messages from history

Requires Message Persistence

Enable Message Persistence for your key in the Admin Portal. See how to enable add-on features.

Remove messages from the history of a specific channel.

Required setting

Enable Delete-From-History for your key in the Admin Portal and initialize the SDK with a secret key.

How to use the start and end parameters

PubNub retrieves messages by searching backward through time (newest to oldest). Because of this, the parameter names are the reverse of their intuitive meaning:

  • start is the newer boundary (higher timetoken value) - search begins here, exclusive
  • end is the older boundary (lower timetoken value) - search stops here, inclusive

When you provide both parameters, start must be a higher timetoken than end.

9:00 AM10:00 AM11:00 AM11:59 AM

Results are always returned in oldest-first order.

Method(s)

To deleteMessages() you can use the following method(s) in the Kotlin SDK.

1pubnub.deleteMessages(
2 channels: List<String>,
3 start: Long,
4 end: Long
5).async { result -> }
* required
ParameterDescription
channels *
Type: List<String>
Default:
n/a
Channels to delete messages from.
start
Type: Long
Default:
n/a
Newer boundary of the query (exclusive). Must be a higher timetoken value than end when both are provided.
end
Type: Long
Default:
n/a
Older boundary of the query (inclusive). Must be a lower timetoken value than start when both are provided.

Sample code

1

Other examples

Delete specific message from history

To delete a specific message, pass the publish timetoken (received from a successful publish) in the End parameter and timetoken +/- 1 in the Start parameter. For example, if 15526611838554310 is the publish timetoken, pass 15526611838554309 in Start and 15526611838554310 in End parameters respectively as shown in the following code snippet.

1

Message counts

Requires Message Persistence

Enable Message Persistence for your key in the Admin Portal. See how to enable add-on features.

Return the number of messages published since the given time. The count is the number of messages with a timetoken greater than or equal to channelsTimetoken.

Unlimited message retention

Only messages from the last 30 days are counted.

Method(s)

Use the following method(s) in the Kotlin SDK:

1pubnub.messageCounts(
2 channels: List<String>,
3 channelsTimetoken: List<Long>
4).async { result -> }
* required
ParameterDescription
channels *
Type: List<String>
Default:
n/a
Channels to fetch the message count.
channelsTimetoken *
Type: List<Long>
Default:
n/a
Array in the same order as channels; a single timetoken applies to all channels; otherwise, lengths must match exactly.

Sample code

1

Returns

MethodDescription
channels
Type: Map<String, Long>
A map with values of Long for each channel. Channels without messages have a count of 0. Channels with 10,000 messages or more have a count of 10000.

Other examples

1

History (deprecated)

Requires Message Persistence

This method requires that Message Persistence is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Deprecated

This method is deprecated and will be removed in a future version. Please use the fetchHistory() method instead.

Method(s)

Use the following method(s) in the Kotlin SDK:

1pubnub.history(
2 channel: String,
3 reverse: Boolean,
4 includeTimetoken: Boolean,
5 includeMeta: Boolean,
6 start: Long,
7 end: Long,
8 count: Int
9).async { result -> }
* required
ParameterDescription
channel *
Type: String
Default:
n/a
Channel to return history messages from.
reverse
Type: Boolean
Default:
false
Traverse from oldest to newest when set to true.
includeTimetoken
Type: Boolean
Default:
false
Whether to include message timetokens in the response.
includeMeta
Type: Boolean
Default:
false
Include the meta object (if provided at publish time) in the response.
start
Type: Long
Default:
n/a
Newer boundary of the query (exclusive). Retrieval begins at this timetoken and moves backward in time. Must be a higher timetoken value than end when both are provided.
end
Type: Long
Default:
n/a
Older boundary of the query (inclusive). Retrieval stops at this timetoken. Must be a lower timetoken value than start when both are provided.
count
Type: Int
Default:
100
Number of historical messages to return.
Using the reverse parameter:

Messages are always returned sorted in ascending time direction from history regardless of reverse. The reverse direction matters when you have more than 100 (or count, if it's set) messages in the time interval, in which case reverse determines the end of the time interval from which it should start retrieving the messages.

Sample code

Retrieve the last 100 messages on a channel:

1

Returns

The history() operation returns a PNHistoryResult which contains the following operations:

MethodDescription
messages
Type: List<PNHistoryItemResult>
List of messages of type PNHistoryItemResult. See PNHistoryItemResult for more details.
startTimetoken
Type: Long
Start timetoken.
endTimetoken
Type: Long
End timetoken.

PNHistoryItemResult

MethodDescription
timetoken
Type: Long?
Timetoken of the message. Is null if not requested.
entry
Type: JsonElement
Message
meta
Type: JsonElement?
Metadata of the message. Is null if not requested, otherwise an empty string if requested but no associated metadata.

Other examples

Use history() to retrieve the three oldest messages by retrieving from the time line in reverse

1

Use history() to retrieve messages newer than a given timetoken by paging from oldest message to newest message starting at a single point in time (exclusive)

1

Use history() to retrieve messages until a given timetoken by paging from newest message to oldest message until a specific end point in time (inclusive)

1

History paging example

1

Include timetoken in history response

1