1
+ import com.google.gson.JsonObject
2
+ import com.pubnub.api.PubNub
3
+ import com.pubnub.api.UserId
4
+ import com.pubnub.api.enums.PNStatusCategory
5
+ import com.pubnub.api.models.consumer.PNStatus
6
+ import com.pubnub.api.models.consumer.pubsub.PNMessageResult
7
+ import com.pubnub.api.models.consumer.pubsub.PNPresenceEventResult
8
+ import com.pubnub.api.v2.callbacks.EventListener
9
+ import com.pubnub.api.v2.callbacks.StatusListener
10
+ import com.pubnub.api.v2.subscriptions.SubscriptionOptions
11
+
12
+ fun main () {
13
+ // snippet.initializePubNubBasic
14
+ // Step 1: Initialize PubNub with configuration
15
+ val config = com.pubnub.api.v2.PNConfiguration .builder(UserId (" myUserId" ), " demo" ).apply {
16
+ publishKey = " demo"
17
+ }.build()
18
+
19
+ val pubnub = PubNub .create(config)
20
+ // snippet.end
21
+
22
+ // Step 2: Define a channel and prepare a message
23
+ val myChannel = " myChannel"
24
+ val myMessage = JsonObject ().apply {
25
+ addProperty(" msg" , " Hello, world" )
26
+ }
27
+
28
+ println (" Message to send: $myMessage " )
29
+
30
+ // snippet.setupEventListenersBasic
31
+ // Step 3: Set up connection status listener
32
+ pubnub.addListener(object : StatusListener {
33
+ override fun status (pubnub : PubNub , status : PNStatus ) {
34
+ when (status.category) {
35
+ PNStatusCategory .PNConnectedCategory -> println (" Connected/Reconnected" )
36
+ PNStatusCategory .PNDisconnectedCategory ,
37
+ PNStatusCategory .PNUnexpectedDisconnectCategory -> println (" Disconnected/Unexpectedly Disconnected" )
38
+ else -> {}
39
+ }
40
+ }
41
+ })
42
+ // snippet.end
43
+
44
+ // snippet.createSubscriptionBasic
45
+ // Step 4: Create a subscription
46
+ val channel = pubnub.channel(myChannel)
47
+ val options = SubscriptionOptions .receivePresenceEvents()
48
+ val subscription = channel.subscription(options)
49
+
50
+ // Step 5: Add event listeners
51
+ subscription.addListener(object : EventListener {
52
+ override fun message (pubnub : PubNub , result : PNMessageResult ) {
53
+ println (" Received message ${result.message.asJsonObject} " )
54
+ }
55
+
56
+ override fun presence (pubnub : PubNub , result : PNPresenceEventResult ) {
57
+ // Handle presence events
58
+ }
59
+ })
60
+
61
+ // Step 6: Activate the subscription
62
+ subscription.subscribe()
63
+ // snippet.end
64
+
65
+ // Wait for connection to establish before publishing
66
+ Thread .sleep(4000 )
67
+
68
+ // snippet.publishMessagesBasic
69
+ // Step 7: Publish a message
70
+ channel.publish(myMessage).async { result ->
71
+ result.onFailure { exception ->
72
+ println (" Error while publishing" )
73
+ exception.printStackTrace()
74
+ }.onSuccess { value ->
75
+ println (" Message sent, timetoken: ${value.timetoken} " )
76
+ }
77
+ }
78
+
79
+ // Keep the program running to receive the published message
80
+ Thread .sleep(2000 )
81
+ // snippet.end
82
+ }
0 commit comments