Skip to content

Commit f06750a

Browse files
committed
Add Kotlin getting started to pubsub
1 parent 9b61523 commit f06750a

File tree

1 file changed

+183
-0
lines changed

1 file changed

+183
-0
lines changed
+183
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
---
2+
title: "Getting started: Pub/Sub in Kotlin"
3+
meta_description: "Get started with Pub/Sub in Kotlin using Ably. Learn how to publish, subscribe, track presence, fetch message history, and manage realtime connections."
4+
meta_keywords: "Pub/Sub Kotlin, Kotlin PubSub, Ably Kotlin SDK, realtime messaging Kotlin, publish subscribe Kotlin, Ably Pub/Sub guide, Kotlin realtime communication, Ably tutorial Kotlin, Kotlin message history, presence API Kotlin, Ably Pub/Sub example, realtime Pub/Sub Kotlin, subscribe to channel Kotlin, publish message Kotlin, Ably CLI Pub/Sub"
5+
---
6+
7+
This guide will get you started with Ably Pub/Sub in Kotlin.
8+
9+
It will take you through the following steps:
10+
11+
* Create a client and establish a realtime connection to Ably.
12+
* Attach to a channel and subscribe to its messages.
13+
* Publish a message to the channel for your client to receive.
14+
* Join and subscribe to the presence set of the channel.
15+
* Retrieve the messages you sent in the guide from history.
16+
* Close a connection to Ably when it is no longer needed.
17+
18+
h2(#prerequisites). Prerequisites
19+
20+
* Sign up for an Ably account.
21+
** Create a new app, and create your first API key.
22+
** Your API key will need the @publish@, @subscribe@, @presence@ and @history@ capabilities.
23+
24+
* Install the Ably CLI:
25+
26+
```[sh]
27+
npm install -g @ably/cli
28+
```
29+
30+
* Run the following to log in to your Ably account and set the default app and API key:
31+
32+
```[sh]
33+
ably login
34+
35+
ably apps switch
36+
ably auth keys switch
37+
```
38+
39+
* Install "JDK": version 11 or greater.
40+
* Create a new project in your IDE and install the Ably Pub/Sub Kotlin SDK. If using Gradle:
41+
42+
```[kotlin]
43+
implementation("io.ably:ably-java:<latest-version>")
44+
```
45+
46+
<aside data-type='note'>
47+
<p>The code examples in this guide include a demo API key. If you wish to interact with the Ably CLI and view outputs within your Ably account, ensure that you replace them with your own API key.</p>
48+
</aside>
49+
50+
h2(#step-1). Step 1: Connect to Ably
51+
52+
Clients establish a connection with Ably when they instantiate an SDK. This enables them to send and receive messages in realtime across channels.
53+
54+
* Open up the "dev console":https://ably.com/accounts/any/apps/any/console of your first app before instantiating your client so that you can see what happens.
55+
56+
* Create an @Main.kt@ file in your project and add the following function to instantiate the SDK and establish a connection to Ably. At the minimum you need to provide an authentication mechanism. Use an API key for simplicity, but you should use token authentication in a production app. A @clientId@ ensures the client is identified, which is required to use certain features, such as presence:
57+
58+
59+
```[kotlin]
60+
import io.ably.lib.realtime.AblyRealtime
61+
import io.ably.lib.realtime.ConnectionEvent
62+
import io.ably.lib.types.ClientOptions
63+
64+
fun getStarted() {
65+
val realtimeClient = AblyRealtime(ClientOptions().apply {
66+
key = "{{API_KEY}}"
67+
clientId = "my-first-client"
68+
})
69+
70+
realtimeClient.connection.once(ConnectionEvent.connected) {
71+
println("Made my first connection!")
72+
}
73+
}
74+
75+
fun main() {
76+
getStarted()
77+
}
78+
```
79+
80+
You can monitor the lifecycle of clients' connections, but for now just log a message to the console to know that the connection attempt was successful. You'll see the message printed to your console, and you can also inspect the connection event in the dev console of your app.
81+
82+
h2(#step-2). Step 2: Subscribe to a channel and publish a message
83+
84+
Messages contain the data that a client is communicating, such as a short 'hello' from a colleague, or a financial update being broadcast to subscribers from a server. Ably uses channels to separate messages into different topics, so that clients only ever receive messages on the channels they are subscribed to.
85+
86+
* Add the following lines to your @getStarted()@ function to create a channel instance and register a listener to subscribe to the channel. Then run it:
87+
88+
```[kotlin]
89+
val channel = ably.channels.get("my-first-channel")
90+
91+
channel.subscribe { message ->
92+
println("Received message: ${message.data}")
93+
}
94+
```
95+
96+
* Use the Ably CLI to publish a message to your first channel. The message will be received by the client you've subscribed to the channel, and be logged to the console.
97+
98+
```[sh]
99+
ably channels publish my-first-channel 'Hello!'
100+
```
101+
102+
* In a new terminal tab, subscribe to the same channel using the CLI:
103+
104+
```[sh]
105+
ably channels subscribe my-first-channel
106+
```
107+
108+
Publish another message using the CLI and you will see that it's received instantly by the client you have running locally, as well as the subscribed terminal instance.
109+
110+
h2(#step-3). Step 3: Join the presence set
111+
112+
Presence enables clients to be aware of one another if they are present on the same channel. You can then show clients who else is online, provide a custom status update for each, and notify the channel when someone goes offline.
113+
114+
* Add the following lines to your @getStarted()@ function to subscribe to, and join, the presence set of the channel. Then run it:
115+
116+
```[kotlin]
117+
channel.presence.subscribe { presenceMessage ->
118+
println("Event type: ${presenceMessage.action} from ${presenceMessage.clientId} with the data ${presenceMessage.data}")
119+
}
120+
121+
channel.presence.enter("I'm here!", null)
122+
```
123+
124+
* In the "dev console":https://ably.com/accounts/any/apps/any/console of your first app, attach to @my-first-channel@. Enter a @clientId@, such as @my-dev-console@, and then join the presence set of the channel. You'll see that @my-first-client@ is already present in the channel. In the console of your IDE you'll see that an event was received when the dev console client joined the channel.
125+
126+
* You can have another client join the presence set using the Ably CLI: @ably channels presence enter my-first-channel --client-id "my-cli" --data '{"status":"online"}'@.
127+
128+
h2(#step-4). Step 4: Retrieve message history
129+
130+
You can retrieve previously sent messages using the history feature. Ably stores all messages for 2 minutes by default in the event a client experiences network connectivity issues. This can be extended for longer if required.
131+
132+
If more than 2 minutes has passed since you published a regular message (excluding the presence events), then you can publish some more before trying out history. You can use the Pub/Sub SDK, Ably CLI or the dev console to do this.
133+
134+
For example, using the Ably CLI to publish 5 messages: @ably channels publish --count 5 my-first-channel "Message number {{.Count}}"@
135+
136+
* Add the following lines to your @getStarted()@ function to retrieve any messages that were recently published to the channel. Then run it:
137+
138+
```[kotlin]
139+
val historyPage = channel.history(null)
140+
val messages = historyPage.items().map { it.data }
141+
println(messages)
142+
```
143+
144+
The output will look similar to the following:
145+
146+
```[json]
147+
[
148+
'Message number 5',
149+
'Message number 4',
150+
'Message number 3',
151+
'Message number 2',
152+
'Message number 1'
153+
]
154+
```
155+
156+
h2(#step-5). Step 5: Close the connection
157+
158+
Connections are automatically closed approximately 2 minutes after no heartbeat is detected by Ably. Explicitly closing connections when they are no longer needed is good practice to help save costs. It will also remove all listeners that were registered by the client.
159+
160+
Note that messages are streamed to clients as soon as they attach to a channel, as long as they have the necessary capabilities. Clients are implicitly attached to a channel when they call @subscribe()@. Detaching from a channel using the @detach()@ method will stop the client from being streamed messages by Ably.
161+
162+
Listeners registered when subscribing to a channel are registered client-side. Unsubscribing by calling @unsubscribe()@ will remove previously registered listeners for that channel. Detaching from a channel has no impact on listeners. As such, if a client reattaches to a channel that they previously registered listeners for, then those listeners will continue to function upon reattachment.
163+
164+
* Add the following to either of the clients to close the connection after a simulated 10 seconds. Run it:
165+
166+
```[kotlin]
167+
Thread.sleep(10_000)
168+
realtimeClient.close()
169+
```
170+
171+
h2(#next). Next steps
172+
173+
Continue to explore the documentation with Kotlin as the selected language:
174+
175+
Read more about the concepts covered in this guide:
176+
177+
* Revisit the basics of "Pub/Sub":/docs/pub-sub
178+
* Explore more "advanced":/docs/pub-sub/advanced Pub/Sub concepts
179+
* Understand realtime "connections":/docs/connect to Ably
180+
* Read more about how to use "presence":/docs/presence-occupancy/presence in your apps
181+
* Fetch message "history":/docs/storage-history/history in your apps
182+
183+
You can also explore the Ably CLI further, or visit the Pub/Sub "API references":/docs/api/realtime-sdk.

0 commit comments

Comments
 (0)