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
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, Integers and Strings. data
should not contain special Unity 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 Serialization
Depending on your JSON library settings, sending structures with circular references (like Vector3) may cause issues. In those cases, you can use the GetJsonSafe()
extension method included in the PubNub namespace.
pubnub.Publish().Channel(defaultChannel).Message(transform.GetJsonSafe()).Execute((a, b) => { });
pubnub.Publish().Channel(defaultChannel).Message(transform.position.GetJsonSafe()).Execute((a, b) => { });
pubnub.Publish().Channel(defaultChannel).Message(transform.localRotation.GetJsonSafe()).Execute((a, b) => { });
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, check 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 (for example,
[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, for example, Publish no faster than 5 messages per second to any one channel.
Method(s)
To Publish a message
you can use the following method(s) in the Unity SDK:
pubnub.Publish()
.Message(object)
.Channel(string)
.ShouldStore(bool)
.Meta(Dictionary<string, object>)
.UsePOST(bool)
.Ttl(int)
.QueryParam(Dictionary<string,object>)
.Execute(System.Action<PNPublishResult, PNStatus>)
Parameter | Type | Required | Description |
---|---|---|---|
Message | object | Yes | The payload. |
Channel | string | Yes | Destination of the Message . |
ShouldStore | bool | Optional | Store in history. If ShouldStore is not specified, then the history configuration on the key is used. |
Meta | Dictionary<string, object> | Optional | Meta data object which can be used with the filtering ability. |
UsePOST | bool | Optional | Use POST to Publish . |
Ttl | int | Optional | Set a per message time to live in storage.
|
QueryParam | Dictionary<string, object> | Optional | Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose. |
Sync | Command | Optional | Block the thread, exception thrown if something goes wrong. |
Async | PNCallback | PNCallback of type PNPublishResult . | |
Execute | System.Action | Optional | System.Action of type PNPublishResult . |
ExecuteAsync | None | Optional | Returns Task<PNResult<PNPublishResult>> . |
Basic Usage
Publish a message to a channel
//Publishing Dictionary
Dictionary<string, float> position = new Dictionary<string, float>();
position.Add("lat", 32F);
position.Add("lng", 32F);
Debug.Log("before pub: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(position));
PNResult<PNPublishResult> publishResponse = await pubnub.Publish()
.Message(position)
.Channel("my_channel")
.ExecuteAsync();
PNPublishResult publishResult = publishResponse.Result;
PNStatus status = publishResponse.Status;
Debug.Log("pub timetoken: " + publishResult.Timetoken.ToString());
Debug.Log("pub status code : " + status.StatusCode.ToString());
Subscribe to the channel
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 PNResult<PNPublishResult>
which contains the following properties:
Property Name | Type | Description |
---|---|---|
Result | PNPublishResult | Returns a PNPublishResult object. |
Status | PNStatus | Returns a PNStatus object. |
PNPublishResult
contains the following properties:
Property Name | Type | Description |
---|---|---|
Timetoken | long | Returns a long representation of the timetoken when the message was published. |
Other Examples
Publish a message to a channel synchronously
//Publishing Dictionary
Dictionary<string, float> position = new Dictionary<string, float>();
position.Add("lat", 32F);
position.Add("lng", 32F);
Debug.Log("before pub: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(position));
pubnub.Publish()
.Message(position)
.Channel("my_channel")
.Execute(new PNPublishResultExt(
(result, status) => {
Debug.Log("pub timetoken: " + result.Timetoken.ToString());
Debug.Log("pub status code : " + status.StatusCode.ToString());
}
show all 16 linesPublish with metadata
string[] arrayMessage = new string[] {
"hello",
"there"
};
pubnub.Publish()
.Message(arrayMessage.ToList())
.Channel("suchChannel")
.ShouldStore(true)
.Meta("<json data as dictionary object>")
.UsePOST(true)
.Execute((result, status) => {
// handle publish result, status always present, result if successful
// status.Error to see if error happened
}
show all 16 linesStore the published message for 10 hours
PNPublishResult res = pubnub.Publish()
.Channel("coolChannel")
.Message("test")
.ShouldStore(true)
.Ttl(10)
.Sync();
Publish with cipher key
PNConfiguration pnConfiguration = new PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.CipherKey = "my_cipherkey";
pnConfiguration.Secure = true;
Pubnub pubnub = new Pubnub(pnConfiguration);
string[] arrayMessage = new string[] {
"hello",
"there"
};
/***Publish same example what we already have. Repeating below***/
pubnub.Publish()
show all 29 linesPublishing messages for receipt on FCM and APNS associated devices, sample payload
public class MobilePayload
{
public Dictionary<string, object> pn_apns;
public Dictionary<string, object> pn_gcm;
public Dictionary<string, object> full_game;
}
Dictionary<string, object> apnsData = new Dictionary<string, object>();
apnsData.Add("aps", new Dictionary<string, object>() {
{ "alert", "Game update 49ers touchdown" },
{ "badge", 2 }
});
apnsData.Add("teams", new string[] { "49ers", "raiders" });
apnsData.Add("score", new int[] { 7, 0 });
show all 53 linesFor more details, refer to Mobile Push.
Fire
The fire endpoint allows the client to send a message to Functions Event Handlers and Illuminate. 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 SDK:
pubnub.Fire()
.Message(object)
.Channel(string)
.Meta(Dictionary<string, object>)
.UsePOST(bool)
.QueryParam(Dictionary<string,object>)
.Execute(System.Action<PNPublishResult, PNStatus>)
Parameter | Type | Required | Description |
---|---|---|---|
Message | object | Yes | The payload. |
Channel | string | Yes | Destination of the message . |
Meta | Dictionary<string, object> | Optional | Meta data object which can be used with the filtering ability. |
UsePOST | bool | Optional | Use POST to Publish . |
QueryParam | Dictionary<string, object> | Optional | Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose. |
Sync | Command | Optional | Block the thread, exception thrown if something goes wrong. |
Async | PNCallback | PNCallback of type PNPublishResult | |
Execute | System.Action | Optional | System.Action of type PNPublishResult |
ExecuteAsync | None | Optional | Returns Task<PNResult<PNPublishResult>> . |
Basic Usage
Fire a message to a channel
string[] arrMessage = new string[] {
"hello",
"there"
};
pubnub.Fire()
.Message(arrMessage.ToList())
.Channel(channel)
.UsePOST(true)
.Execute((result, status) => {
if (status.Error) {
// something bad happened.
Debug.Log("error happened while publishing: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status));
} else {
Debug.Log("publish worked! timetoken: " + result.Timetoken.ToString());
show all 18 linesSignal
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 SDK:
pubnub.Signal()
.Message(object)
.Channel(string)
.Execute(System.Action<PNPublishResult, PNStatus>)
Parameter | Type | Required | Description |
---|---|---|---|
Message | object | Yes | The payload. |
Channel | string | Yes | Destination of the Message . |
Execute | System.Action | Optional | System.Action of type PNPublishResult . |
ExecuteAsync | None | Optional | Returns Task<PNResult<PNPublishResult>> . |
Basic Usage
Signal a message to a channel
Dictionary<string, string> myMessage = new Dictionary<string, string>();
myMessage.Add("msg", "Hello Signals");
pubnub.Signal()
.Message(myMessage)
.Channel("foo")
.Execute((result, status) => {
if (status.Error) {
Debug.Log(status.ErrorData.Information);
} else {
Debug.Log(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.
Unsubscribing from all channels
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 SDK:
pubnub.Subscribe<string>()
.Channels(Array|List<string>)
.ChannelGroups(Array|List<string>)
.WithTimetoken(long)
.WithPresence()
.QueryParam(Dictionary<string,object>)
.Execute(System.Action<PNPublishResult, PNStatus>)
Parameter | Type | Required | Description |
---|---|---|---|
Channels | Array or List<string> | Optional | Subscribe to Channels , Either Channels or ChannelGroups is required. |
ChannelGroups | Array or List<string> | Optional | Subscribe to ChannelGroups , Either Channels or ChannelGroups is required. |
WithTimetoken | long | Optional | Pass a Timetoken . |
WithPresence | Command | Optional | Also subscribe to related presence information. |
QueryParam | Dictionary<string, object> | Optional | Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose. |
Execute | System.Action | Optional | System.Action of type PNPublishResult . |
Basic Usage
Subscribe to a channel:
pubnub.Subscribe<string>()
.Channels(new string[] {
// subscribe to channels
"my_channel"
})
.Execute();
Event listeners
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
PNMessageResult
PNMessageResult<T>
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 execution. |
Operation | PNOperationType | Operation type of the request. |
AffectedChannels | List<string> | A list of affected channels in the operation. |
AffectedChannelGroups | List<string> | A list of affected channel groups in the operation. |
The Subscribe()
operation returns a PNMessageResult<T>
for messages which contains the following operations:
Property Name | Type | Description |
---|---|---|
Message | 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:
Property Name | 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 | Dictionary | 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 . |
Join | string[] | List of channels when the event is interval . |
Timeout | string[] | List of channels when the event is interval . |
Leave | string[] | List of channels when the event is interval . |
HereNowRefresh | bool | Flag to indicate whether HereNow fetch is needed. |
Other Examples
Basic subscribe with logging
PNConfiguration pnConfiguration = new PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
// subscribeKey from admin panel
pnConfiguration.SubscribeKey = "my_subkey"; // required
// publishKey from admin panel (only required if publishing)
pnConfiguration.PublishKey = "my_pubkey";
// secretKey (only required for access operations)
pnConfiguration.LogVerbosity = PNLogVerbosity.BODY;
Pubnub pubnub = new Pubnub(pnConfiguration);
pubnub.Subscribe<string>()
.Channels(new string[] {
// subscribe to channels
"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<string>()
.Channels(new string[] {
// subscribe to channels information
"my_channel1",
"my_channel2"
})
.Execute();
Subscribing to a Presence channel
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your 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 named my_channel
would have the presence channel named my_channel-pnpres
.
pubnub.Subscribe<string>()
.Channels(new string[] {
// subscribe to channels
"my_channel"
})
.WithPresence() // also subscribe to related presence information
.Execute();
Sample Responses
Join Event
{
"Event": "join",
"Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"Timestamp": 1345546797,
"Occupancy": 2,
"State": null,
"Channel":" my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
"HereNowRefresh": false
}
Leave Event
{
"Event": "leave",
"Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"Timestamp": 1345546797,
"Occupancy": 1,
"State": null,
"Channel": "my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
"HereNowRefresh": false
}
Timeout Event
{
"Event": "timeout",
"Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"Timestamp": 1345546797,
"Occupancy": 0,
"State": null,
"Channel": "my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
"HereNowRefresh": false
}
Custom Presence Event (State Change)
{
"Event": "state-change",
"Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"Timestamp": 1345546797,
"Occupancy": 1,
"State": {
"isTyping": true
},
"Channel": "my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
show all 17 linesInterval Event
{
"Event": "interval",
"Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"Timestamp": 1345546797,
"Occupancy": 2,
"State": null,
"Channel": "my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
"HereNowRefresh": false
}
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
- timed out
For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:
{
"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": ["uuid2", "uuid3"],
"Timeout": ["uuid1"],
"Leave": null,
"HereNowRefresh": false
}
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 a here_now_refresh
boolean field set to true
. This indicates to the user that they should do a hereNow
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-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal (with Enable Wildcard Subscribe checked). Read the support page on enabling add-on features on your 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 for a.b
, a.c
, a.x
. The *
portion refers to any part of the channel string name after the dot (.)
.
pubnub.Subscribe<string>()
.Channels(new string[] {
// subscribe to channels information
"foo.*"
})
.Execute();
Wildcard grants and revokes
Only one level (a.*
) of using wildcards is supported. If you grant on *
or a.b.*
, the grant will treat *
or a.b.*
as a single channel named either *
or a.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, like a.*
.
Subscribing with State
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Required UserId
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
PNConfiguration pnConfiguration = new PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.SubscribeKey = "demo";
pnConfiguration.PublishKey = "demo";
Pubnub pubnub = new Pubnub(pnConfiguration);
SubscribeCallbackListener listener = new()
listener.onStatus += (pubnub, status) => {
if (status.Category == PNStatusCategory.PNConnectedCategory) {
Dictionary<string, object> data = new Dictionary<string, object>();
data.Add("FieldA", "Awesome");
data.Add("FieldB", 10);
pubnub.SetPresenceState()
.Channels(new string[] { "awesomeChannel" })
.ChannelGroups(new string[] { "awesomeChannelGroup" })
.State(data)
show all 28 linesSubscribe to a channel group
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
pubnub.Subscribe<string>()
.Channels(new string[] {
// subscribe to channels
"ch1",
"ch2"
})
.ChannelGroups(new string[] {
// subscribe to channel groups
"cg1",
"cg2"
})
.WithTimetoken(1337L) // optional, pass a timetoken
.WithPresence() // also subscribe to related presence information
.Execute();
Subscribe to the presence channel of a channel group
note
This method requires both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
pubnub.Subscribe<string>()
.ChannelGroups(new string[] {
// subscribe to channel groups
"cg1",
"cg2"
})
.WithTimetoken(1337L) // optional, pass a timetoken
.WithPresence() // also subscribe to related presence information
.Execute();
Subscribe with a Custom Type
Unity supports subscribing with custom types. However only one type of message can be subscribed for a given channel. If you want to subscribe different types of messages for the same channel, then subscribing using the generic type as string
is the recommended option.
public class Phone
{
public string Number { get; set; }
public string Extenion { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public PhoneType PhoneType { get; set; }
}
public enum PhoneType
{
Home,
Mobile,
Work
}
show all 64 linesUnsubscribe
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.
Unsubscribing from all channels
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 SDK:
pubnub.Unsubscribe<string>()
.Channels(Array)
.ChannelGroups(Array)
.QueryParam(Dictionary<string,object>)
.Execute()
Parameter | Type | Required | Description |
---|---|---|---|
Channels | Array | Optional | Unsubscribe to channels , Either Channels or ChannelGroups is required |
ChannelGroups | Array | Optional | Unsubscribe to channel groups, Either channels or channelGroup is required |
QueryParam | Dictionary<string, object> | Optional | Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose. |
Execute | Command | Yes | Command that will execute Unsubscribe . |
Basic Usage
Unsubscribe from a channel:
pubnub.Unsubscribe<string>()
.Channels(new string[] {
"my_channel"
})
.Execute();
Event listeners
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
None
Other Examples
Unsubscribing from multiple channels
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
pubnub.Unsubscribe<string>()
.Channels(new string[] {
"ch1",
"ch2",
"ch3"
})
.ChannelGroups(new string[] {
"cg1",
"cg2",
"cg3"
})
.Execute();
Example Response
{
"Category": "PNDisconnectedCategory",
"ErrorData": null,
"Error": false,
"StatusCode": 200,
"Operation": "PNUnsubscribeOperation",
"TlsEnabled": false,
"Uuid": null,
"AuthKey": null,
"Origin": "ps.pndsn.com",
"ClientRequest": null,
"AffectedChannels": ["ch1","ch2","ch3"],
"AffectedChannelGroups": ["cg1","cg2","cg3"]
}
Unsubscribe from a channel group
pubnub.Unsubscribe<string>()
.ChannelGroups(new string[] {
"cg1",
"cg2",
"cg3"
})
.Execute();
Example Response
{
"Category": "PNDisconnectedCategory",
"ErrorData": null,
"Error": false,
"StatusCode": 200,
"Operation": "PNUnsubscribeOperation",
"TlsEnabled": false,
"Uuid": null,
"AuthKey": null,
"Origin": "ps.pndsn.com",
"ClientRequest": null,
"AffectedChannels": [],
"AffectedChannelGroups": ["cg1","cg2","cg3"]
}
Unsubscribe All
Unsubscribe from all channels and all channel groups
Method(s)
pubnub.UnsubscribeAll<string>()
.QueryParam(Dictionary<string,object>)
Parameter | Type | Required | Description |
---|---|---|---|
QueryParam | Dictionary<string, object> | Optional | Dictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose. |
Basic Usage
pubnub.UnsubscribeAll();
Returns
None