Subscribe to and unsubscribe from a PubSub topic
- Last UpdatedApr 08, 2026
- 1 minute read
This scenario guides you through the steps required to subscribe to and unsubscribe from a PubSub topic.
To identify the code associated with each step, see the code comments in the Example code section.
To subscribe to and unsubscribe from a PubSub topic
- Open the Program.cs file from the created project.
- Open a PubSub connection.
- Confirm there is a connection with the PubSub system.
- Subscribe to a PubSub topic with a finite or non-finite timeout.
- Receive data from the underlying PubSub connection. Data is blocked until available or the timeout has expired.
- Unsubscribe from a PubSub topic by using one of the following methods:
- Using the Disconnect method.
// Disconnect, which will unsubscribe, clean up, and disconnect from the engine. pubsubConnection.Disconnect(); - Once the using block is finished, disposing the connection will remove the publisher, clean up, and disconnect from the engine. If a using block is used, calling Disconnect explicity is optional.
- Using the Disconnect method.
Example code
internal void AddSubscriptionWithConnectionFactoryAndUnsubscribe()
{
try
{
IPubSubConnectionFactory pubSubConnectionFactory = new PubSubConnectionFactory();
// Open a connection.
using (var pubsubConnection = pubSubConnectionFactory.OpenConnection())
{
// Check if there is connection with the PubSub system.
if (pubsubConnection.IsConnected())
{
var topic = "es.realtime.db.analog.DeviceRollupAnalog01.curval";
// Subscribe to a PubSub topic with a finite or non-finite timeout.
var subscription = pubsubConnection.Subscribe(topic, Timeout.InfiniteTimeSpan, true);
// Receive data from the underlying PubSub connection. Data is blocked until available or the timeout has expired.
var pubsubMsg = subscription.Receive();
Console.WriteLine(quot;Current topic has: {pubsubMsg.GetDouble()} value.");
// Unsubscribe from a PubSub topic.
pubsubConnection.Disconnect();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}
}