pub struct Pubsub<T: PubsubTopic, P: Clone> { /* private fields */ }Expand description
A publish-subscribe system that allows multiple subscribers to receive messages published to specific topics.
The Pubsub struct is the main interface for creating topics, publishing messages, and managing subscriptions. It uses an internal Arc reference to shared state, allowing multiple clones of the Pubsub instance to share the same underlying subscription data.
§Type Parameters
T- The topic type, must implement PubsubTopic (Clone + Hash + Eq)P- The payload type, must implement Clone
§Examples
// let pubsub = Pubsub::new();
// let subscriber = pubsub.subscribe(vec!["topic1", "topic2"]).await;
// pubsub.publish("topic1", "Hello, world!".to_owned()).await;Implementations§
Source§impl<T: PubsubTopic, P: Clone> Pubsub<T, P>
impl<T: PubsubTopic, P: Clone> Pubsub<T, P>
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new Pubsub instance with empty topic subscriptions.
This initializes the internal shared state and returns a new Pubsub instance that can be used to manage topics and subscriptions.
§Examples
// let pubsub = Pubsub::new();Sourcepub async fn subscribe(&self, topics: Vec<T>) -> Subscriber<T, P>
pub async fn subscribe(&self, topics: Vec<T>) -> Subscriber<T, P>
Subscribes to one or more topics and returns a new Subscriber instance.
§Arguments
topics- A vector of topics to subscribe to. The subscriber will receive messages published to any of these topics.
§Returns
A new Subscriber instance that can be used to receive messages for the subscribed topics.
§Example
// let pubsub = Pubsub::new();
// let subscriber = pubsub.subscribe(vec!["topic1", "topic2"]).await;Sourcepub async fn publish(&self, topic: T, payload: P)
pub async fn publish(&self, topic: T, payload: P)
Publishes a message to a specific topic.
§Arguments
topic- The topic to publish the message to. Subscribers subscribed to this topic will receive the message.payload- The message payload to send to subscribers.
§Example
// let pubsub = Pubsub::new();
// pubsub.publish("topic1", "Hello, world!".to_owned()).await;Trait Implementations§
Source§impl<T: PubsubTopic, P: Clone> Drop for Pubsub<T, P>
Implements the Drop trait for Pubsub to ensure proper cleanup when the last instance is dropped.
impl<T: PubsubTopic, P: Clone> Drop for Pubsub<T, P>
Implements the Drop trait for Pubsub to ensure proper cleanup when the last instance is dropped.
When the last strong reference to the Pubsub’s inner data is dropped, this implementation:
- Checks if this is the last strong reference (Arc::strong_count == 1)
- If so, iterates through all topics and their subscribers
- Closes each subscriber’s channel to prevent them from being stuck waiting for messages
This ensures that any remaining subscribers will receive an error on their next recv() call rather than blocking indefinitely, allowing them to clean up their resources properly.