Publish/Subscribe API for PubNub Unity SDK
The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 100ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.
For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.
Publish
Description
The Publish()
function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid PublishKey
at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.
Publish Anytime
It's not required to be subscribed to a channel in order to publish to that channel.
Message Data:
The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. data
should not contain special Unity V4 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Don't JSON serialize!
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
Message Size:
The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.
If the message you publish exceeds the configured size, you will receive the following message:
Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]
For further details please check: https://support.pubnub.com/hc/en-us/articles/360051495932-Calculating-Message-Payload-Size-Before-Publish
Message Publish Rate:
Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels:
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably:
There are some best practices to ensure messages are delivered when publishing to a channel:
- Publish to any given channel in a serial manner (not concurrently).
- Check that the return code is success (e.g.
[1,"Sent","136074940..."]
) - Publish the next message only after receiving a success return code.
- If a failure code is returned (
[0,"blah","<timetoken>"]
), retry the publish. - Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
- Throttle publish bursts in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.
Method(s)
To Publish a message
you can use the following method(s) in the Unity V4 SDK:
pubnub.Publish().Channel(string).Message(object).UsePost(bool).ShouldStore(bool).Meta(Dictionary<string,string>).PublishAsIs(bool).Ttl(int).QueryParam(Dictionary<string,string>).Async()
Parameter Type Required Defaults Description Channel
string Yes Destination of the message
.Message
object Yes The payload. UsePOST
bool Optional false
Use POST to publish
.ShouldStore
bool Optional account default
Store in history.
IfshouldStore
is not specified, then the history configuration on the key is used.Meta
Dictionary<string,string> Optional Not set
Meta
data object which can be used with the filtering ability.PublishAsIs
bool Optional false
It should be set to true
when you are going toPublish
a JSON serialized string.
By default it is set tofalse
and the SDK takes care of JSON serializing the message for you.Ttl
int Optional Set a per message time to live in storage. - If
shouldStore
=true
, andTtl
=0
, the message is stored with no expiry time. - If
shouldStore
=true
andTtl
=X
(X
is an Integer value), the message is stored with an expiry time ofX
hours. - If
shouldStore
=false
, theTtl
parameter is ignored. - If
Ttl
is not specified, then expiration of the message defaults back to the expiry value for the key.
QueryParam
Dictionary<string, string> Optional QueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API. Async
PNCallback Optional PNCallback
of typePNPublishResult
- If
Basic Usage
Publish a message to a channel:
pubnub.Publish()
.Channel("my_channel")
.Message("Hello from the PubNub Unity SDK")
.Async((result, status) => {
if (!status.Error) {
Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken));
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
});
Note
Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
Returns
The Publish()
operation returns a PNPublishResult
which contains the following operations:
Method | Type | Description |
---|---|---|
Timetoken | long | Returns a long representation of the timetoken when the message was published. |
Other Examples
-
Dictionary<string, string> metaDict = new Dictionary<string, string>(); metaDict.Add("region", "east"); pubnub.Publish() .Channel("my_channel") .Message("Hello from the PubNub Unity SDK") .Meta(metaDict) .Async((result, status) => { if (!status.Error) { Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken)); } else { Debug.Log(status.Error); Debug.Log(status.ErrorData.Info); } });
Store the published message for 10 hours
pubnub.Publish() .Channel("my_channel") .Message("Hello from the PubNub Unity SDK") .Ttl(10) .Async((result, status) => { if (!status.Error) { Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken)); } else { Debug.Log(status.Error); Debug.Log(status.ErrorData.Info); } });
-
You can use the helper method as an input to the
Message
parameter, to format the payload for publishing Push messages. For more info on the helper method, check Create Push Payload Helper SectionCreatePushPayloadHelper cpph = new CreatePushPayloadHelper(); PNAPSData aps = new PNAPSData(); aps.Alert = "alert"; aps.Badge = 1; aps.Sound = "ding"; aps.Custom = new Dictionary<string, object>(){ {"aps_key1", "aps_value1"}, {"aps_key2", "aps_value2"}, }; PNAPNSData apns = new PNAPNSData(); apns.APS = aps; apns.Custom = new Dictionary<string, object>(){ {"apns_key1", "apns_value1"}, {"apns_key2", "apns_value2"}, }; PNAPNS2Data apns2One = new PNAPNS2Data(); apns2One.CollapseID = "invitations"; apns2One.Expiration = "2019-12-13T22:06:09Z"; apns2One.Version = "v1"; apns2One.Targets = new List<PNPushTarget>(){ new PNPushTarget(){ Environment = PNPushEnvironment.Development, Topic = "com.meetings.chat.app", ExcludeDevices = new List<string>(){ "device1", "device2", } } }; PNAPNS2Data apns2Two = new PNAPNS2Data(); apns2Two.CollapseID = "invitations"; apns2Two.Expiration = "2019-12-15T22:06:09Z"; apns2Two.Version = "v2"; apns2Two.Targets = new List<PNPushTarget>(){ new PNPushTarget(){ Environment = PNPushEnvironment.Production, Topic = "com.meetings.chat.app", ExcludeDevices = new List<string>(){ "device3", "device4", } } }; List<PNAPNS2Data> apns2 = new List<PNAPNS2Data>(){ apns2One, apns2Two, }; PNFCMData fcm = new PNFCMData(); fcm.Custom = new Dictionary<string, object>(){ {"fcm_key1", "fcm_value1"}, {"fcm_key2", "fcm_value2"}, }; fcm.Data = new PNFCMDataFields(){ Summary = "summary", Custom = new Dictionary<string, object>(){ {"fcm_data_key1", "fcm_data_value1"}, {"fcm_data_key2", "fcm_data_value2"}, } }; Dictionary<string, object> commonPayload = new Dictionary<string, object>(); commonPayload = new Dictionary<string, object>(){ {"common_key1", "common_value1"}, {"common_key2", "common_value2"}, }; Dictionary<string, object> payload = cpph.SetAPNSPayload(apns, apns2).SetFCMPayload(fcm).SetCommonPayload(commonPayload).BuildPayload(); pubnub.Publish() .Channel("my_channel") .Message(payload) .Async((result, status) => { if (!status.Error) { Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken)); } else { Debug.Log(status.Error); Debug.Log(status.ErrorData.Info); } });
Fire
Description
The fire endpoint allows the client to send a message to PubNub Functions Event Handlers. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire()
isn't replicated, and so won't be received by any subscribers to the channel. The message is also not stored in history.
Method(s)
To Fire a message
you can use the following method(s) in the Unity V4 SDK:
pubnub.Fire().Channel(string).Message(object).Meta(Dictionary<string,string>).PublishAsIs(bool).usePOST(bool).Ttl(int).QueryParam(Dictionary<string,string>).Async()
Parameter Type Required Defaults Description Channel
string Yes Destination of the message
.Message
object Yes The payload. Meta
Dictionary<string,string> Optional Not set
Meta
data object which can be used with the filtering ability.PublishAsIs
bool Optional false
It should be set to true
when you are going toPublish
a JSON.usePOST
bool Optional false
Use POST to publish
.Ttl
int Optional Set a per message time to live in storage. - If shouldStore =
true
, andttl
= 0, the message is stored with no expirytime
. - If shouldStore =
true
andttl
= X (X is an Integer value), the message is stored with an expiry time of X hours. - If shouldStore =
false
, the ttlparameter is ignored. - If ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
QueryParam
Dictionary<string, string> Optional QueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API. Async
PNCallback Optional PNCallback
of typePNPublishResult
- If shouldStore =
Basic Usage
Fire a message to a channel:
pubnub.Fire()
.Channel("my_channel")
.Message("test fire message")
.Async((result, status) => {
if(status.Error){
Debug.Log (status.Error);
Debug.Log (status.ErrorData.Info);
} else {
Debug.Log (string.Format("Fire Timetoken: {0}", result.Timetoken));
}
});
Signal
Description
The signal()
function is used to send a signal to all subscribers of a channel.
By default, signals are limited to a message payload size of 64
bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please contact support.
Method(s)
To Signal a message
you can use the following method(s) in the Unity V4 SDK:
pubnub.Signal().Message(object).Channel(string).Async()
Parameter Type Required Description Message
object Yes The payload. Channel
string Yes Destination of the Message
.Async
PNCallback Optional PNCallback
of typePNSignalResult
Basic Usage
Signal a message to a channel:
pubnub.Signal()
.Channel("my_channel")
.Message("test signal message")
.Async((result, status) => {
if(status.Error){
Debug.Log (status.Error);
Debug.Log (status.ErrorData.Info);
} else {
Debug.Log (string.Format("Signal Timetoken: {0}", result.Timetoken));
}
});
Response
Property Name | Type | Description |
---|---|---|
Timetoken | long | Returns a long representation of the timetoken when the message was signaled. |
Subscribe
Receive messages
Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.
For more information about adding a listener, refer to the Event Listeners section.
Description
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel
. To subscribe to a channel
the client must send the appropriate SubscribeKey
at initialization.
By default a newly subscribed client will only receive messages published to the channel after the Subscribe()
call completes.
If a client gets disconnected from a channel, it can automatically attempt to reconnect to that channel
and retrieve any available messages that were missed during that period. This can be achieved by setting ReconnectionPolicy
to PNReconnectionPolicy.LINEAR
, when initializing the client.
Warning
Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken
and thus, there could be some gaps in the subscription that may lead to message loss.
Method(s)
To Subscribe to a channel
you can use the following method(s) in the Unity V4 SDK:
pubnub.Subscribe().Channels(List<string>).ChannelGroups(List<string>).SetTimeToken(long).WithPresence(bool).QueryParam(Dictionary<string,string>).Execute(Command);
Parameter Type Required Description Channels
List Optional Subscribe to channels
, Eitherchannel
orchannelGroup
is required.ChannelGroups
List Optional Subscribe to channel groups
, Eitherchannel
orchannelGroup
is required.SetTimetoken
long Optional Pass a timetoken.
WithPresence
bool Optional Also subscribe to related presence information. QueryParam
Dictionary<string, string> Optional QueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API. Execute()
Command Yes Command that will execute
subscribe
.
Basic Usage
Subscribe to a channel:
pubnub.Subscribe()
.Channels(new List<string>() {
"my_channel"
})
.Execute();
Note
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Returns
Note
PNMessageResult
is returned in the Listeners
The Subscribe()
operation returns a PNStatus
which contains the following operations:
Property Name | Type | Description |
---|---|---|
Category | PNStatusCategory | Details of PNStatusCategory are here |
Error | bool | This is true if an error occurred in the execution of the operation. |
ErrorData | PNErrorData | Error data of the exception (if Error is true ) |
StatusCode | int | Status code of the excution. |
Operation | PNOperationType | Operation type of the request. |
AffectedChannels | List | A list of affected channels in the operation. |
AffectedChannelGroups | List | A list of affected channel groups in the operation. |
The Subscribe()
operation returns a PNMessageResult
, for both Publish
and Signal
messages, which contains the following operations:
Method | Type | Description |
---|---|---|
Payload | object | The message sent on the channel . |
Subscription | string | The channel group or wildcard subscription match (if exists). |
Channel | string | The channel for which the message belongs. |
Timetoken | long | Timetoken for the message. |
UserMetadata | object | User metadata . |
The Subscribe()
operation returns a PNPresenceEventResult
from presence which contains the following operations:
Method | Type | Description |
---|---|---|
Event | string | Events like join , leave , timeout , state-change , interval . |
UUID | string | UUID for the event. |
Timestamp | long | Timestamp for the event. |
Occupancy | int | Current occupancy . |
State | object | State of the UUID . |
Subscription | string | The channel group or wildcard subscription match (if exists). |
Channel | string | The channel for which the message belongs. |
Timetoken | long | Timetoken of the message. |
UserMetadata | object | User metadata . |
Other Examples
-
PNConfiguration pnConfiguration = new PNConfiguration (); pnConfiguration.SubscribeKey = "my_subkey"; pnConfiguration.PublishKey = "my_pubkey"; pnConfiguration.LogVerbosity = PNLogVerbosity.BODY; pubnub = new PubNub (pnConfiguration); pubnub.Subscribe ().Channels(new List<string> (){"my_channel"}).Execute();
Subscribing to multiple channels:
It's possible to subscribe to more than one channel using the Multiplexing feature. The example shows how to do that using an array to specify the channel names.
Alternative subscription methods
You can also use Wildcard Subscribe and Channel Groups to subscribe to multiple channels at a time. To use these features, the Stream Controller add-on must be enabled on your keyset in the Admin Portal.
pubnub.Subscribe(). Channels(new List<string> (){"my_channel", "my_channel2"}) .Execute();
- Subscribing to a Presence channel: Requires Presence add-onRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending
-pnpres
to the channel name. For example the channel namedmy_channel
would have the presence channel namedmy_channel-pnpres
. Presence data can be observed inside theSubscribeCallback#message(PubNub, PNMessageResult)
callback.pubnub.Subscribe() .Channels(new List<string>() { "my_channel" }) .WithPresence() .Execute();
Sample Responses
Join Event
pubnub.SubscribeCallback += (sender, e) => { SubscribeEventEventArgs mea = e as SubscribeEventEventArgs; if(mea.PresenceEventResult.Event.Equals("join")){ Debug.Log(mea.PresenceEventResult.UUID); Debug.Log(mea.PresenceEventResult.Timestamp); Debug.Log(mea.PresenceEventResult.Occupancy); } };
Leave Event
pubnub.SubscribeCallback += (sender, e) => { SubscribeEventEventArgs mea = e as SubscribeEventEventArgs; if(mea.PresenceEventResult.Event.Equals("leave")){ Debug.Log(mea.PresenceEventResult.UUID); Debug.Log(mea.PresenceEventResult.Timestamp); Debug.Log(mea.PresenceEventResult.Occupancy); } };
Timeout Event
pubnub.SubscribeCallback += (sender, e) => { SubscribeEventEventArgs mea = e as SubscribeEventEventArgs; if(mea.PresenceEventResult.Event.Equals("timeout")){ Debug.Log(mea.PresenceEventResult.UUID); Debug.Log(mea.PresenceEventResult.Timestamp); Debug.Log(mea.PresenceEventResult.Occupancy); } };
Custom Presence Event (State Change)
pubnub.SubscribeCallback += (sender, e) => { SubscribeEventEventArgs mea = e as SubscribeEventEventArgs; if(mea.PresenceEventResult.Event.Equals("state-change")){ Debug.Log(mea.PresenceEventResult.UUID); Debug.Log(mea.PresenceEventResult.Timestamp); Debug.Log(mea.PresenceEventResult.Occupancy); } };
Interval Event
pubnub.SubscribeCallback += (sender, e) => { SubscribeEventEventArgs mea = e as SubscribeEventEventArgs; if(mea.PresenceEventResult.Event.Equals("interval")){ Debug.Log(mea.PresenceEventResult.UUID); Debug.Log(mea.PresenceEventResult.Timestamp); Debug.Log(mea.PresenceEventResult.Occupancy); } };
When a channel is in interval mode with
presence_deltas
pnconfig
flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.- joined
- left
- timedout
For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:
pubnub.SubscribeCallback += (sender, e) => { SubscribeEventEventArgs mea = e as SubscribeEventEventArgs; if (mea.PresenceEventResult.Event.Equals("interval")) { Debug.Log(mea.PresenceEventResult.UUID); Debug.Log(mea.PresenceEventResult.Timestamp); Debug.Log(mea.PresenceEventResult.Occupancy) ; Debug.Log(string.Join(",",mea.PresenceEventResult.Join.ToArray())); Debug.Log(string.Join(",",mea.PresenceEventResult.Timeout.ToArray())); } };
If the full interval message is greater than
30KB
(since the max publish payload is∼32KB
), none of the extra fields will be present. Instead there will be ahere_now_refresh
boolean field set totrue
. This indicates to the user that they should do ahereNow
request to get the complete list of users present in the channel.{ "Event": "interval", "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e", "Timestamp": <unix timestamp>, "Occupancy": <# users in channel>, "State": null, "Channel": "my_channel", "Subscription": "", "Timetoken": 15034141109823424, "UserMetadata": null, "Join": null, "Timeout": null, "Leave": null, "HereNowRefresh": true }
- Wildcard subscribe to channels: Requires Stream Controller add-onRequires that the Stream Controller add-on is enabled with Enable Wildcard Subscribe checked for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to
a.*
you will get all messages fora.b
,a.c
,a.x
. The wildcarded*
portion refers to any portion of the channel string name after thedot (.)
.pubnub.Subscribe() .Channels(new List<string> (){"foo.*"}) .Execute();
Wildcard grants and revokes
Only one level (
a.*
) of wildcarding is supported. If you grant on*
ora.b.*
, the grant will treat*
ora.b.*
as a single channel named either*
ora.b.*
. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, likea.*
. - Subscribing with State: Requires Presence add-onRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.Dictionary<string, object> state = new Dictionary<string, object>(); state.Add("k", "v"); PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.SubscribeKey = "my_subkey"; pnConfiguration.PublishKey = "my_pubkey"; pubnub = new PubNub(pnConfiguration); pubnub.SubscribeCallback += (sender, e) => { SubscribeEventEventArgs mea = e as SubscribeEventEventArgs; if (mea.Status != null) { if (mea.Status.Category.Equals(PNStatusCategory.PNConnectedCategory)) { pubnub.SetPresenceState() .ChannelGroups(channelGroupList) .State(state) .Async ((result, status) => { if (status.Error) { Assert.Fail("SetPresenceState failed"); } }); } } if (mea.MessageResult != null) { Debug.Log ("In Example, SubscribeCallback in message" + mea.MessageResult.Channel + mea.MessageResult.Payload); } if (mea.PresenceEventResult != null) { Debug.Log("In Example, SubscribeCallback in presence" + mea.PresenceEventResult.Channel + mea.PresenceEventResult.Occupancy + mea.PresenceEventResult.Event); } }; pubnub.Subscribe() .Channels(new List<string> () { "my_channel" }) .Execute();
- Subscribe to a channel group: Requires Stream Controller add-onRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-pubnub.Subscribe() .ChannelGroups(new List<string> (){"my_channel_group"}) .Execute();
- Subscribe to the presence channel of a channel group: Requires Stream Controller and Presence add-onRequires that both Stream Controller and Presence add-ons are enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-pubnub.Subscribe() .ChannelGroups(new List<string> (){"family"}) .WithPresence() .Execute();
Unsubscribe
Description
When subscribed to a single channel, this function causes the client to issue a leave
from the channel
and close any open socket to the PubNub Network. For multiplexed channels, the specified channel
(s) will be removed and the socket remains open until there are no more channels remaining in the list.
Warning
Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken
and thus, there could be some gaps in the subscription that may lead to message loss.
Method(s)
To Unsubscribe from a channel
you can use the following method(s) in the Unity V4 SDK:
pubnub.Unsubscribe().ChannelGroups(List<string>).Channels(List<string>).QueryParam(Dictionary<string,string>).Async(Command)
Parameter Type Required Description ChannelGroups
List Optional Unsubscribe to channel groups, Either channel
orchannelGroup
is required.Channels
List Optional Unsubscribe to channels
, Eitherchannel
orchannelGroup
is required.QueryParam
Dictionary<string, string> Optional QueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API. Async
Command Yes Command that will execute
unsubscribe
.
Basic Usage
Unsubscribe from a channel:
pubnub.Unsubscribe()
.ChannelGroups(new List<string>(){
"my_channel_group"
})
.Channels(new List<string>() {
"my_channel"
})
.Async((result, status) => {
if (status.Error) {
Debug.Log(string.Format("Unsubscribe Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
} else {
Debug.Log(string.Format("DateTime {0}, In Unsubscribe, result: {1}", DateTime.UtcNow, result.Message));
}
});
Note
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Rest Response from Server
The Unsubscribe() operation returns a PNLeaveRequestResult which contains the following operations:
Method | Type | Description |
---|---|---|
Message | string | The message from the operation. |
Other Examples
- Unsubscribing from multiple channels. Requires Stream Controller add-onRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-pubnub.Unsubscribe() .Channels(new List<string> (){"my_channel1", "my_channel2"}) .Async((result, status) => { if(status.Error){ Debug.Log (string.Format("In Example, Unsubscribe Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category)); } else { Debug.Log (string.Format("DateTime {0}, In Unsubscribe, result: {1}", DateTime.UtcNow, result.Message)); } });
Method Type Description Message
string The message
from the operation. Unsubscribe from a channel group
pubnub.Unsubscribe() .ChannelGroups(new List<string> (){"my_channel_group", "my_channel_group_1"}) .Async((result, status) => { if(status.Error){ Debug.Log (string.Format("Unsubscribe Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category)); } else { Debug.Log (string.Format("DateTime {0}, In Unsubscribe, result: {1}", DateTime.UtcNow, result.Message)); } });
Method Type Description Message
string The message
from the operation.
Unsubscribe All
Description
Unsubscribe from all channels and all channel groups
Method(s)
pubnub.UnsubscribeAll().QueryParam(Dictionary<string,string>).Async(Command)
Parameter Type Required Description QueryParam
Dictionary<string, string> Optional QueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API. Async
Command Yes Command that will unsubscribe
from all subscribed channels.
Basic Usage
pubnub.UnsubscribeAll()
.Async((result, status) => {
if(status.Error){
Debug.Log (string.Format("UnsubscribeAll Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
} else {
Debug.Log (string.Format("DateTime {0}, In UnsubscribeAll, result: {1}", DateTime.UtcNow, result.Message));
}
});
Returns
None