PubNub Kotlin SDK 8.0.0

This page outlines the steps to follow to create a simple Hello, World application with PubNub. This covers the basics of integrating PubNub in your application: setting up a connection to PubNub, and sending and receiving messages.

PubNub account

Sign in or create an account to create an app on the Admin Portal and get the keys to use in your application.

When you create a new app, the first set of keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.

Download the SDK

Download the SDK from any of the following sources:

Use Maven

To integrate PubNub into your project using Maven, add the following dependency in your pom.xml:

<dependency>
<groupId>com.pubnub</groupId>
<artifactId>pubnub-gson</artifactId>
<version>8.0.0</version>
</dependency>

Use Gradle

To integrate PubNub into your project using Gradle (including Android Studio), add the following dependency in your build.gradle file:

implementation 'com.pubnub:pubnub-kotlin:8.0.0'

Use a .jar file

To use Pubnub, simply copy the Pubnub-8.0.0 .jar file into your project's libs directory.

https://github.com/pubnub/kotlin/releases/tag/8.0.0

Get the source code

https://github.com/pubnub/kotlin/

Configure ProGuard

If you're using ProGuard, configure it as follows.

# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
show all 65 lines

Configure PubNub

In the IDE of your choice, create a new Kotlin project. In that project, create a new App class with the following content. This is the minimum configuration you need to send and receive messages with PubNub.

Make sure to replace myPubKey and mySubKey with your app's publish and subscribe keys from the Admin Portal.

val config = PNConfiguration(UserId("myUserId")).apply {
subscribeKey = "mySubKey"
publishKey = "myPubKey"
}

For more information, refer to the Configuration section of the SDK documentation.

Add event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

In addition to setting up listeners, the following code prints out the content of every received message.

// Adds a listener for connection status updates
pubnub.addListener(object : StatusListener() {
override fun status(pubnub: PubNub, status: PNStatus) {
println("Status category: ${status.category}")
println("Status operation: ${status.operation}")
println("Status error: ${status.error}")
}
})

// Adds a listener for receiving messages and presence events
pubnub.addListener(object : EventListener {
// Handle new messages
override fun message(pubnub: PubNub, message: PNMessageResult) {
println("Message payload: ${message.message}")
println("Message channel: ${message.channel}")
show all 30 lines

For more information, refer to the Listeners section of the SDK documentation.

Publish and subscribe

To receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone subscribed to that channel.

The publish() method uses the channel and message variables that you can see in the following code.

To subscribe to real-time updates, you must create a subscription or a subscription set and send a subscribe() call.

It is best to define the subscription before you introduce the listeners and send the subscribe() call, so place the relevant code in the appropriate places within your code.

// Initialize the PubNub client
val pubnub = PubNub(...)

// Define the channel you want to subscribe to
val channel = pubnub.channel("myChannel")

// Define subscription options if necessary (optional step, depending on SDK capabilities)
val options = SubscriptionOptions.receivePresenceEvents() // Example option

// Assuming a conceptual way to explicitly create a subscription
val subscription = channel.subscription(options)

// Activate the subscription to start receiving messages
subscription.subscribe()

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Putting it all together

Your main() function should now look similar to the following:

import com.google.gson.JsonObject
import com.pubnub.api.PNConfiguration
import com.pubnub.api.PubNub
import com.pubnub.api.enums.PNOperationType
import com.pubnub.api.enums.PNStatusCategory
import com.pubnub.api.models.consumer.PNStatus
import com.pubnub.api.models.consumer.pubsub.PNMessageResult
import com.pubnub.api.models.consumer.pubsub.PNPresenceEventResult

fun main() {
val config = PNConfiguration(UserId("myUserId")).apply {
subscribeKey = "mySubKey"
publishKey = "myPubKey"
}

show all 78 lines

Now, run your app to see if you did everything correctly.

Save the App class and run it with gradle run in the terminal. You can use the one that is built in your IDE or the one that your operating system provides. You should see output similar to the following:

Message to send: {"msg":"Hello, world"}
Received message: {"msg":"Hello, world"}
The content of the message is: Hello, world

Congratulations! You've just subscribed to a channel and sent your first message.

Walkthrough

Instead of focusing on the order in which you wrote the code, let's focus on the order in which it runs. The app you just created does a few things:

  • configures a PubNub connection
  • adds the status, message, and presence event listeners
  • subscribes to a channel
  • publishes a message

Configuring PubNub

The following code is the minimum configuration you need to send and receive messages with PubNub. For more information, refer to the PNConfiguration section of the SDK documentation.

val config = PNConfiguration(UserId("myUserId")).apply {
subscribeKey = "mySubKey"
publishKey = "myPubKey"

val pubnub = PubNub(config)

Add event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

You added three listeners to the app: status, message, and presence. Status listens for status events and when it receives an event of type PNConnectedCategory, it publishes the message.message listens for incoming messages on a particular channel. When it receives a message, the app simply prints the received message. This is why you see "Hello, World" displayed in the console. The presence listener reacts to events connected to presence. In this example, the presence listener is a no-operation.

pubnub.addListener(object : StatusListener() {

override fun status(pubnub: PubNub, status: PNStatus) {
when (status.category) {
PNStatusCategory.PNUnexpectedDisconnectCategory -> {
// This event happens when radio / connectivity is lost.
}
PNStatusCategory.PNConnectedCategory -> {
// Connect event. You can do stuff like publish,
// knowing it'll go through, or just use the connected
// event to confirm you're subscribed for UI/internal notifications, etc.
channelName?.let {
val messageJsonObject = JsonObject().apply {
addProperty("msg", "Hello, World")
}
show all 59 lines

For more information, refer to the Listeners section of the SDK documentation.

Publishing and subscribing

PubNub uses the Publish/Subscribe model for real-time communication. This model involves two essential parts:

  • Channels are transient paths over which your data is transmitted
  • Messages contain the data you want to transmit to one or more recipients

When you want to receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel. In this example, you subscribe to a channel named myChannel.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB. PubNub will, in most cases, deliver your message to its intended recipients in fewer than 100 ms regardless of their location. You can also share files up to 5MB.

val myChannel = "awesomeChannel"
val myMessage = JsonObject().apply {
addProperty("msg", "Hello, world") // Creating the message to publish
}

println("Message to send: $myMessage")

// Publishing a message to the provided channel
pubnub.publish(
channel = myChannel, // The channel to which the message is being published
message = myMessage // The message object to publish
).async { result, status ->
// Logging the status for visibility
println(status)

show all 24 lines

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Next steps

You have just learned how to use the Kotlin SDK to send and receive messages using PubNub. Next, take a look at the SDK's reference documentation which covers PubNub API in more detail.

Last updated on