---
source_url: https://www.pubnub.com/docs/sdks/kotlin/api-reference/misc
title: Utility Methods API for Kotlin SDK
updated_at: 2026-06-19T11:37:43.236Z
sdk_name: PubNub Kotlin SDK
sdk_version: 13.4.0
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Utility Methods API for Kotlin SDK

PubNub Kotlin SDK, use the latest version: 13.4.0

Install:

```bash
Add PubNub dependency to your build@13.4.0
```

:::warning Breaking changes in v9.0.0
PubNub Kotlin SDK version 9.0.0 unifies the codebases for Kotlin and [Java](https://www.pubnub.com/docs/sdks/java) SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted [status events](https://www.pubnub.com/docs/sdks/kotlin/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](https://www.pubnub.com/docs/sdks/kotlin/migration-guides/kotlin-v9-migration-guide).
:::

The methods on this page are utility methods that don't fit into other categories.

:::tip 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.
```kotlin
val channel = pubnub.channel("channelName")
channel.publish("This SDK rules!").async { result ->
    result.onFailure { exception ->
        // Handle error
    }.onSuccess { value ->
        // Handle successful method result
    }
}
```
:::

## Create push payload

This method creates the push payload for use in the appropriate endpoint calls.

### Method(s)

```kotlin
val pushPayloadHelper = PushPayloadHelper()

val fcmPayloadV2 = FCMPayloadV2()
val apnsPayload = APNSPayload()

pushPayloadHelper.fcmPayloadV2 = fcmPayloadV2
pushPayloadHelper.apnsPayload = apnsPayload
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| apnsPayload | APNSPayload | Optional |  | Set APNS and APNS2 Payload. Associated devices will receive only the data supplied here within the `pn_apns` key. |
| fcmPayloadV2 | FCMPayloadV2 | Optional |  | Set FCM Payload V2. Associated devices will receive only the data supplied here within the `pn_fcm` key. |
| commonPayload | Map<String, | Optional |  | Set common Payload. Native PubNub subscribers will receive the data provided here, together with the `pn_apns` and `pn_fcm` objects. |
| build | Map<String, | Yes |  | Builds the payload from the values set using the parameters. |

### Sample code

:::tip 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.
:::

#### Create push payload

```kotlin
import com.pubnub.api.PubNub
import com.pubnub.api.UserId
import com.pubnub.api.enums.PNPushEnvironment
import com.pubnub.api.models.consumer.push.payload.PushPayloadHelper
import com.pubnub.api.v2.PNConfiguration

/**
 * This example demonstrates how to use the PushPayloadHelper class in PubNub Kotlin SDK.
 *
 * PushPayloadHelper creates properly formatted payloads for FCM (Android) and APNS (iOS)
 * push notifications to deliver to mobile devices.
 *
 * Note: This is a compilation-only example as it requires valid push notification tokens
 * to actually send notifications to devices.
 */
fun main() {
    println("PubNub PushPayloadHelper Example")
    println("================================")

    // 1. Configure PubNub
    val userId = UserId("push-helper-demo-user")
    val config = PNConfiguration.builder(userId, "demo").apply {
        publishKey = "demo"
    }.build()

    // 2. Create PubNub instance
    val pubnub = PubNub.create(config)

    // 3. Create basic push notification payloads
    createBasicPushPayload(pubnub)

    // 4. Create advanced push notification payloads
    createAdvancedPushPayload(pubnub)

    // Clean up
    pubnub.destroy()
}

/**
 * Creates a basic push notification payload with simple alerts
 */
fun createBasicPushPayload(pubnub: PubNub) {
    println("\n# Basic Push Notification Payload Example")

    // Create an instance of PushPayloadHelper
    val pushPayloadHelper = PushPayloadHelper()

    // Basic FCM V2 payload for Android
    val fcmPayloadV2 = PushPayloadHelper.FCMPayloadV2().apply {
        notification = PushPayloadHelper.FCMPayloadV2.Notification().apply {
            title = "Basic Notification"
            body = "This is a simple push notification"
        }
    }
    pushPayloadHelper.fcmPayloadV2 = fcmPayloadV2

    // Basic APNS payload for iOS
    val apnsPayload = PushPayloadHelper.APNSPayload().apply {
        aps = PushPayloadHelper.APNSPayload.APS().apply {
            // Simple string alert
            alert = "This is a simple push notification"
            badge = 1
            sound = "default"
        }
    }
    pushPayloadHelper.apnsPayload = apnsPayload

    // Add common payload for regular PubNub subscribers
    pushPayloadHelper.commonPayload = mapOf(
        "message" to "This is a simple push notification",
        "type" to "alert"
    )

    // Build the final payload
    val payload = pushPayloadHelper.build()

    println("Basic Push Payload Structure:")
    println("- FCM (Android): ${payload["pn_fcm"] != null}")
    println("- APNS (iOS): ${payload["pn_apns"] != null}")
    println("- Common fields: ${payload.keys.filter { it != "pn_fcm" && it != "pn_apns" }}")

    // In a real application, you would publish this payload
    // to a channel where devices are registered for push notifications
    println("\nTo send this notification, you would use:")
    println("pubnub.publish(")
    println("    channel = \"notifications_channel\",")
    println("    message = payload")
    println(").async { result -> /* Handle result */ }")
}

/**
 * Creates an advanced push notification payload with rich content and targeting
 */
fun createAdvancedPushPayload(pubnub: PubNub) {
    println("\n# Advanced Push Notification Payload Example")

    // Create an instance of PushPayloadHelper
    val pushPayloadHelper = PushPayloadHelper()

    // Advanced FCM V2 payload with additional features
    val fcmV2 = PushPayloadHelper.FCMPayloadV2().apply {
        // Basic notification part
        notification = PushPayloadHelper.FCMPayloadV2.Notification().apply {
            title = "Meeting Reminder"
            body = "Your meeting with the team starts in 15 minutes"
            image = "https://example.com/meeting-image.png"
        }

        // Android specific configuration
        android = PushPayloadHelper.FCMPayloadV2.AndroidConfig().apply {
            priority = PushPayloadHelper.FCMPayloadV2.AndroidConfig.AndroidMessagePriority.HIGH
            ttl = "3600s" // Notification expires after 1 hour

            // Android specific notification settings
            notification = PushPayloadHelper.FCMPayloadV2.AndroidConfig.AndroidNotification().apply {
                clickAction = "OPEN_MEETING_ACTIVITY"
                color = "#4285F4"
                channelId = "meeting_reminders"
                sound = "meeting_alert"
                // Set higher priority for this notification
                notificationPriority =
                    PushPayloadHelper.FCMPayloadV2.AndroidConfig.AndroidNotification.NotificationPriority.PRIORITY_HIGH
            }
        }

        // Data payload that will be delivered to the app
        data = mapOf(
            "meeting_id" to "12345",
            "room" to "Conference Room A",
            "start_time" to "2025-03-25T14:15:00Z",
            "participants" to "Alice,Bob,Charlie"
        )
    }
    pushPayloadHelper.fcmPayloadV2 = fcmV2

    // Advanced APNS payload for iOS
    val apnsPayload = PushPayloadHelper.APNSPayload().apply {
        // APS is the Apple Push Notification Service payload
        aps = PushPayloadHelper.APNSPayload.APS().apply {
            // Create a structured alert with title and body instead of simple string
            val alertMap = mapOf(
                "title" to "Meeting Reminder",
                "body" to "Your meeting with the team starts in 15 minutes",
                "subtitle" to "Calendar Notification"
            )
            alert = alertMap

            badge = 3
            sound = "meeting_alert.aiff"
        }

        // Custom APNS payload fields
        custom = mapOf(
            "meeting_id" to "12345",
            "room" to "Conference Room A",
            "content-available" to 1,
            "category" to "MEETING_INVITATION",
            "thread-id" to "calendar-events"
        )

        // APNS2 configurations for targeting specific apps/devices
        apns2Configurations = listOf(
            PushPayloadHelper.APNSPayload.APNS2Configuration().apply {
                collapseId = "meeting-12345" // Group related notifications
                expiration = "2025-03-25T14:30:00Z" // When the notification expires
                version = "v2"
                targets = listOf(
                    PushPayloadHelper.APNSPayload.APNS2Configuration.Target().apply {
                        environment = PNPushEnvironment.DEVELOPMENT // or PRODUCTION
                        topic = "com.example.calendar" // Your app's bundle ID
                        // Exclude specific devices if needed
                        excludeDevices = listOf("device-token-to-exclude-1", "device-token-to-exclude-2")
                    }
                )
            }
        )
    }
    pushPayloadHelper.apnsPayload = apnsPayload

    // Common payload for all subscribers (both mobile push and regular PubNub)
    pushPayloadHelper.commonPayload = mapOf(
        "message" to "Your meeting with the team starts in 15 minutes",
        "meeting_id" to "12345",
        "type" to "meeting_reminder",
        "action_required" to true
    )

    // Build the final payload
    val payload = pushPayloadHelper.build()

    println("Advanced Push Payload Created:")
    println("- Contains FCM payload: ${payload["pn_fcm"] != null}")
    println("- Contains APNS payload: ${payload["pn_apns"] != null}")
    println("- Common fields count: ${payload.keys.filter { it !in listOf("pn_fcm", "pn_apns") }.size}")

    // Examples of using the payload
    println("\nTo send this notification to all subscribers on a channel:")
    println("pubnub.publish(")
    println("    channel = \"team_notifications\",")
    println("    message = payload")
    println(").async { result -> /* Handle response */ }")

    // Output note about testing
    println("\nNote: To actually receive these notifications on devices, you would need:")
    println("1. Valid FCM/APNs credentials configured in the PubNub Admin Portal")
    println("2. Devices registered for push notifications using pubnub.addPushNotificationsOnChannels()")
    println("3. Valid device tokens for the target devices")
}
```

### Response

The `PushPayloadHelper#build()` operation returns a `Map<String, Any>` which can be passed directly as the `message` parameter to the `pubnub.publish()` method.

## Destroy

Destroy frees up the threads and allows for clean exit.

### Method(s)

```kotlin
destroy()
```

### Sample code

```kotlin
pubNub.destroy()
```

### Returns

None

## Get subscribed channels groups

Returns all the subscribed channel groups in a `List<String>`.

### Method(s)

To Get Subscribe Channel Groups you can use the following method(s) in the Kotlin SDK:

```kotlin
fun getSubscribedChannelGroups(): List<String>
```

### Sample code

```kotlin
val subscribedChannelGroups = pubNub.getSubscribedChannelGroups()
```

### Response

```json
["channel1", "channel2"]
```

## Get subscribed channels

Returns all the subscribed channels in a `List<String>`.

### Method(s)

To Get Subscribe Channels you can use the following method(s) in the Kotlin SDK:

```kotlin
fun getSubscribedChannels(): List<String>
```

### Sample code

```kotlin
val subscribedChannels = pubNub.getSubscribedChannels()
```

### Response

```json
["channel1", "channel2"]
```

## Disconnect

Call the `disconnect()` method to force the SDK to stop all requests to PubNub server when there are active subscribe channels.

### Method(s)

To `disconnect()` the data transmission you can use the following method(s) in Kotlin SDK.

```kotlin
disconnect()
```

This method doesn't take any arguments.

### Sample code

```kotlin
pubNub.disconnect()
```

## Reconnect

Call the `reconnect()` method to force the SDK to try and reach out PubNub.

### Method(s)

To `reconnect()` the data you can use the following method(s) in Kotlin SDK.

```kotlin
reconnect(timeout: Long)
```

| Parameter | Description |
| --- | --- |
| `timeout`Type: `Long` | Timetoken to reconnect from. |

### Sample code

```kotlin
pubNub.reconnect()
// or
val timetoken = 17276954606232118L // Example timetoken received in publish/signal response
pubNub.reconnect(timetoken)
```

## Timetoken to date

The `timetokenToInstant()` method of the `TimetokenUtil` class converts a PubNub timetoken (a unique identifier for each message sent and received in a PubNub channel that is a number of 100-nanosecond intervals since January 1, 1970) to an `Instant` object representing the corresponding date and time.

Use this method when you want to display the timetoken of each message or event in the message history in a human-readable format.

### Method signature

```kotlin
TimetokenUtil.timetokenToInstant(timetoken: Long): Instant
```

#### Input

| Parameter | Description |
| --- | --- |
| `timetoken` *Type: `Long`Default: n/a | Represents the PubNub timetoken to convert into a human-readable date format. |

#### Output

| Type | Description |
| --- | --- |
| `Instant` | The human-readable date representation of the timetoken. |

### Sample code

Convert a timetoken value of `17276954606232118` to a human-readable date and time format.

```kotlin
val timetoken: Long = 17276954606232118
val instant: Instant = TimetokenUtil.timetokenToInstant(timetoken)
val localDateTimeInUTC = instant.toLocalDateTime(TimeZone.UTC)

println("PubNub timetoken: $timetoken")
println("Current date: ${localDateTimeInUTC.date}")
println("Current time: ${localDateTimeInUTC.time}")
```

## Date to timetoken

The `instantToTimetoken()` method of the `TimetokenUtil` class converts the `Instant` object representing the corresponding date and time into a PubNub timetoken (a unique identifier for each message sent and received in a PubNub channel that is a number of 100-nanosecond intervals since January 1, 1970).

Use this method to represent a specific date and time as a PubNub timetoken value, for example, to retrieve messages from a PubNub channel at a particular date and time.

### Method signature

```kotlin
TimetokenUtil.instantToTimetoken(instant: Instant): Long
```

#### Input

| Parameter | Description |
| --- | --- |
| `instant` *Type: `Instant`Default: n/a | Represents the date and time to convert into a PubNub timetoken. |

#### Output

| Type | Description |
| --- | --- |
| `Long` | Converted timetoken value. |

### Sample code

Convert a human-readable date and time, `September 30, 2024 12:12:24 GMT`, to a timetoken.

```kotlin
val localDateTime = LocalDateTime(
    year = 2024,
    month = 9,
    day = 30,
    hour = 12,
    minute = 12,
    second = 44,
    nanosecond = 123456789
)

val zone = TimeZone.currentSystemDefault()
val instant: Instant = TimetokenUtil.localDateTimeToInstant(localDateTime, zone)
val timetoken = TimetokenUtil.instantToTimetoken(instant)

println("Current date: ${localDateTime.date}")
println("Current time: ${localDateTime.time}")
println("PubNub timetoken: $timetoken")
```

## LocalDateTime to Instant

The `localDateTimeToInstant()` method of the `TimetokenUtil` class converts a `kotlinx.datetime.LocalDateTime` in the provided `kotlinx.datetime.TimeZone` into a PubNub `Instant`.

Use this method when you have a local date and time and need a PubNub `Instant` without opting in to experimental Kotlin time APIs.

### Method signature

```kotlin
TimetokenUtil.localDateTimeToInstant(localDateTime: LocalDateTime, timeZone: TimeZone): Instant
```

#### Input

| Parameter | Description |
| --- | --- |
| `localDateTime` *Type: `LocalDateTime`Default: n/a | The local date and time to convert. |
| `timeZone` *Type: `TimeZone`Default: n/a | The time zone of the provided `LocalDateTime`. |

#### Output

| Type | Description |
| --- | --- |
| `Instant` | A PubNub `Instant` representing the corresponding moment in time. |

### Sample code

The [Date to timetoken](#date-to-timetoken) sample shows `localDateTimeToInstant()` in use as part of a full `LocalDateTime` to timetoken conversion.

```kotlin
val localDateTime = LocalDateTime(
    year = 2024,
    month = 9,
    day = 30,
    hour = 12,
    minute = 12,
    second = 44,
    nanosecond = 123456789
)

val zone = TimeZone.currentSystemDefault()
val instant: Instant = TimetokenUtil.localDateTimeToInstant(localDateTime, zone)
val timetoken = TimetokenUtil.instantToTimetoken(instant)

println("Current date: ${localDateTime.date}")
println("Current time: ${localDateTime.time}")
println("PubNub timetoken: $timetoken")
```

## LocalDateTime to timetoken

The `localDateTimeToTimetoken()` method of the `TimetokenUtil` class converts a `kotlinx.datetime.LocalDateTime` in the provided `kotlinx.datetime.TimeZone` directly to a PubNub timetoken.

Use this method when you need a timetoken from a local date and time in a single step, for example, to [retrieve historical messages](https://www.pubnub.com/docs/sdks/kotlin/api-reference/storage-and-playback) starting from a specific date.

### Method signature

```kotlin
TimetokenUtil.localDateTimeToTimetoken(localDateTime: LocalDateTime, timeZone: TimeZone): Long
```

#### Input

| Parameter | Description |
| --- | --- |
| `localDateTime` *Type: `LocalDateTime`Default: n/a | The local date and time to convert. |
| `timeZone` *Type: `TimeZone`Default: n/a | The time zone of the provided `LocalDateTime`. |

#### Output

| Type | Description |
| --- | --- |
| `Long` | Converted timetoken value. |

### Sample code

This method combines `localDateTimeToInstant()` and `instantToTimetoken()` into a single call. The [Date to timetoken](#date-to-timetoken) sample shows the equivalent two-step approach.

```kotlin
val localDateTime = LocalDateTime(
    year = 2024, month = 9, day = 30,
    hour = 12, minute = 12, second = 44,
    nanosecond = 123456789
)

val zone = TimeZone.currentSystemDefault()
val timetoken: Long = TimetokenUtil.localDateTimeToTimetoken(localDateTime, zone)

println("PubNub timetoken: $timetoken")
```

## Unix timestamp to timetoken

The `unixToTimetoken()` method of the `TimetokenUtil` class converts a Unix timestamp (a number of seconds since January 1, 1970) to a PubNub timetoken (a unique identifier for each message sent and received in a PubNub channel that is a number of 100-nanosecond intervals since January 1, 1970).

Use this method when you need a timetoken to [retrieve historical messages](https://www.pubnub.com/docs/sdks/kotlin/api-reference/storage-and-playback) with a specific timestamp range from Message Persistence.

### Method signature

This method takes the following parameters:

```kotlin
TimetokenUtil.unixToTimetoken(unixTime: Long): Long 
```

#### Input

| Parameter | Description |
| --- | --- |
| `unixTime` *Type: `Long`Default: n/a | Represents the Unix timestamp to convert into a PubNub timetoken. |

#### Output

| Type | Description |
| --- | --- |
| `Long` | Converted timetoken value. |

### Sample code

Convert a Unix timestamp value of `1727866935316` representing `2024-10-02 11:02:15.316` to PubNub timetoken:

```kotlin
val unixTime = 1727866935316
val timetoken: Long = TimetokenUtil.unixToTimetoken(unixTime)
val instant: Instant = TimetokenUtil.timetokenToInstant(timetoken)
val localDateTime = instant.toLocalDateTime(TimeZone.UTC)

println("Current date: ${localDateTime.date}")
println("Current time: ${localDateTime.time}")
println("PubNub timetoken: $timetoken")
```

## Timetoken to Unix timestamp

The `timetokenToUnix()` method of the `TimetokenUtil` class converts a PubNub timetoken (a unique identifier for each message sent and received in a PubNub channel that is a number of 100-nanosecond intervals since January 1, 1970) to a Unix timestamp (a number of seconds since January 1, 1970).

Use this method to convert PubNub timetoken for use in another context or system that requires a Unix timestamp.

### Method signature

```kotlin
TimetokenUtil.timetokenToUnix(timetoken: Long): Long 
```

#### Input

| Parameter | Description |
| --- | --- |
| `timetoken` *Type: `Long`Default: n/a | Represents the PubNub timetoken to convert into a Unix timestamp. |

#### Output

| Type | Description |
| --- | --- |
| `Long` | Converted Unix timestamp value. |

### Sample code

Convert a PubNub timetoken `17276954606232118` representing `2024-09-30 11:24:20.623211800` to Unix time:

```kotlin
val timetoken = 17276954606232118
val unixTime = TimetokenUtil.timetokenToUnix(timetoken)
val instant = Instant.fromEpochMilliseconds(unixTime)
val localDateTime = instant.toLocalDateTime(TimeZone.UTC)

println("Current date: ${localDateTime.date}")
println("Current time: ${localDateTime.time}")
println("PubNub timetoken: $timetoken")
```