Skip to content

Commit f98ed52

Browse files
committed
docs(inline): change client to pubnub in inline docs
refactor(examples): refactor `subscribe` example Separate `subscribe` example into two to show separately `subscribe` feature and `presence state` maintenance with subscribe.
1 parent c3b921f commit f98ed52

File tree

9 files changed

+268
-118
lines changed

9 files changed

+268
-118
lines changed

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,10 @@ required-features = ["default"]
165165

166166
[[example]]
167167
name = "subscribe"
168+
required-features = ["default", "subscribe"]
169+
170+
[[example]]
171+
name = "subscribe_with_presence_state"
168172
required-features = ["default", "subscribe", "presence"]
169173

170174
[[example]]

examples/subscribe.rs

Lines changed: 23 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
use std::collections::HashMap;
2-
31
use futures::StreamExt;
42
use serde::Deserialize;
53
use std::env;
@@ -26,7 +24,7 @@ async fn main() -> Result<(), Box<dyn snafu::Error>> {
2624
let publish_key = env::var("SDK_PUB_KEY")?;
2725
let subscribe_key = env::var("SDK_SUB_KEY")?;
2826

29-
let client = PubNubClientBuilder::with_reqwest_transport()
27+
let pubnub = PubNubClientBuilder::with_reqwest_transport()
3028
.with_keyset(Keyset {
3129
subscribe_key,
3230
publish_key: Some(publish_key),
@@ -40,22 +38,9 @@ async fn main() -> Result<(), Box<dyn snafu::Error>> {
4038

4139
println!("running!");
4240

43-
client
44-
.set_presence_state(HashMap::<String, String>::from([
45-
(
46-
"is_doing".to_string(),
47-
"Nothing... Just hanging around...".to_string(),
48-
),
49-
("flag".to_string(), "false".to_string()),
50-
]))
51-
.channels(["my_channel".into(), "other_channel".into()].to_vec())
52-
.user_id("user_id")
53-
.execute()
54-
.await?;
55-
5641
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
5742

58-
let subscription = client.subscription(SubscriptionParams {
43+
let subscription = pubnub.subscription(SubscriptionParams {
5944
channels: Some(&["my_channel", "other_channel"]),
6045
channel_groups: None,
6146
options: Some(vec![SubscriptionOptions::ReceivePresenceEvents]),
@@ -65,11 +50,13 @@ async fn main() -> Result<(), Box<dyn snafu::Error>> {
6550

6651
// Attach connection status to the PubNub client instance.
6752
tokio::spawn(
68-
client
53+
pubnub
6954
.status_stream()
7055
.for_each(|status| async move { println!("\nstatus: {:?}", status) }),
7156
);
7257

58+
// Example of the "global" listener for multiplexed subscription object from
59+
// PubNub client.
7360
tokio::spawn(subscription.stream().for_each(|event| async move {
7461
match event {
7562
Update::Message(message) | Update::Signal(message) => {
@@ -96,48 +83,44 @@ async fn main() -> Result<(), Box<dyn snafu::Error>> {
9683
}
9784
}));
9885

99-
tokio::spawn(subscription_clone.stream().for_each(|event| async move {
100-
match event {
101-
Update::Message(message) | Update::Signal(message) => {
86+
// Explicitly listen only for real-time `message` updates.
87+
tokio::spawn(
88+
subscription_clone
89+
.messages_stream()
90+
.for_each(|message| async move {
10291
// Deserialize the message payload as you wish
10392
match serde_json::from_slice::<Message>(&message.data) {
10493
Ok(message) => println!("(b) defined message: {:?}", message),
10594
Err(_) => {
10695
println!("(b) other message: {:?}", String::from_utf8(message.data))
10796
}
10897
}
109-
}
110-
Update::Presence(presence) => {
111-
println!("(b) presence: {:?}", presence)
112-
}
113-
Update::AppContext(object) => {
114-
println!("(b) object: {:?}", object)
115-
}
116-
Update::MessageAction(action) => {
117-
println!("(b) message action: {:?}", action)
118-
}
119-
Update::File(file) => {
120-
println!("(b) file: {:?}", file)
121-
}
122-
}
123-
}));
98+
}),
99+
);
100+
101+
// Explicitly listen only for real-time `file` updates.
102+
tokio::spawn(
103+
subscription_clone
104+
.files_stream()
105+
.for_each(|file| async move { println!("(b) file: {:?}", file) }),
106+
);
124107

125108
// Sleep for a minute. Now you can send messages to the channels
126109
// "my_channel" and "other_channel" and see them printed in the console.
127-
// You can use the publish example or [PubNub console](https://www.pubnub.com/docs/console/)
110+
// You can use the publishing example or [PubNub console](https://www.pubnub.com/docs/console/)
128111
// to send messages.
129112
tokio::time::sleep(tokio::time::Duration::from_secs(15)).await;
130113

131114
// You can also cancel the subscription at any time.
132115
// subscription.unsubscribe();
133116

134117
println!("\nDisconnect from the real-time data stream");
135-
client.disconnect();
118+
pubnub.disconnect();
136119

137120
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
138121

139122
println!("\nReconnect to the real-time data stream");
140-
client.reconnect(None);
123+
pubnub.reconnect(None);
141124

142125
// Let event engine process unsubscribe request
143126
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
@@ -149,7 +132,7 @@ async fn main() -> Result<(), Box<dyn snafu::Error>> {
149132
println!(
150133
"\nUnsubscribe from all data streams. To restore requires `subscription.subscribe(None)` call." );
151134
// Clean up before complete work with PubNub client instance.
152-
client.unsubscribe_all();
135+
pubnub.unsubscribe_all();
153136
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
154137

155138
Ok(())
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
use std::collections::HashMap;
2+
3+
use futures::StreamExt;
4+
use serde::Deserialize;
5+
use std::env;
6+
7+
use pubnub::subscribe::{SubscriptionOptions, SubscriptionParams};
8+
use pubnub::{
9+
dx::subscribe::Update,
10+
subscribe::{EventEmitter, EventSubscriber},
11+
Keyset, PubNubClientBuilder,
12+
};
13+
14+
#[derive(Debug, Deserialize)]
15+
struct Message {
16+
// Allowing dead code because we don't use these fields
17+
// in this example.
18+
#[allow(dead_code)]
19+
url: String,
20+
#[allow(dead_code)]
21+
description: String,
22+
}
23+
24+
#[tokio::main]
25+
async fn main() -> Result<(), Box<dyn snafu::Error>> {
26+
let publish_key = env::var("SDK_PUB_KEY")?;
27+
let subscribe_key = env::var("SDK_SUB_KEY")?;
28+
29+
let pubnub = PubNubClientBuilder::with_reqwest_transport()
30+
.with_keyset(Keyset {
31+
subscribe_key,
32+
publish_key: Some(publish_key),
33+
secret_key: None,
34+
})
35+
.with_user_id("user_id")
36+
.with_filter_expression("some_filter")
37+
.with_heartbeat_value(100)
38+
.with_heartbeat_interval(5)
39+
.build()?;
40+
41+
println!("running!");
42+
43+
// Setting up state which will be associated with the user id as long as he is
44+
// subscribed and not timeout.
45+
pubnub
46+
.set_presence_state(HashMap::<String, String>::from([
47+
(
48+
"is_doing".to_string(),
49+
"Nothing... Just hanging around...".to_string(),
50+
),
51+
("flag".to_string(), "false".to_string()),
52+
]))
53+
.channels(["my_channel".into(), "other_channel".into()].to_vec())
54+
.user_id("user_id")
55+
.execute()
56+
.await?;
57+
58+
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
59+
60+
let subscription = pubnub.subscription(SubscriptionParams {
61+
channels: Some(&["my_channel", "other_channel"]),
62+
channel_groups: None,
63+
options: Some(vec![SubscriptionOptions::ReceivePresenceEvents]),
64+
});
65+
subscription.subscribe(None);
66+
let subscription_clone = subscription.clone_empty();
67+
68+
// Attach connection status to the PubNub client instance.
69+
tokio::spawn(
70+
pubnub
71+
.status_stream()
72+
.for_each(|status| async move { println!("\nstatus: {:?}", status) }),
73+
);
74+
75+
tokio::spawn(subscription.stream().for_each(|event| async move {
76+
match event {
77+
Update::Message(message) | Update::Signal(message) => {
78+
// Deserialize the message payload as you wish
79+
match serde_json::from_slice::<Message>(&message.data) {
80+
Ok(message) => println!("(a) defined message: {:?}", message),
81+
Err(_) => {
82+
println!("(a) other message: {:?}", String::from_utf8(message.data))
83+
}
84+
}
85+
}
86+
Update::Presence(presence) => {
87+
println!("(a) presence: {:?}", presence)
88+
}
89+
Update::AppContext(object) => {
90+
println!("(a) object: {:?}", object)
91+
}
92+
Update::MessageAction(action) => {
93+
println!("(a) message action: {:?}", action)
94+
}
95+
Update::File(file) => {
96+
println!("(a) file: {:?}", file)
97+
}
98+
}
99+
}));
100+
101+
// Explicitly listen only for real-time `message` updates.
102+
tokio::spawn(
103+
subscription_clone
104+
.messages_stream()
105+
.for_each(|message| async move {
106+
// Deserialize the message payload as you wish
107+
match serde_json::from_slice::<Message>(&message.data) {
108+
Ok(message) => println!("(b) defined message: {:?}", message),
109+
Err(_) => {
110+
println!("(b) other message: {:?}", String::from_utf8(message.data))
111+
}
112+
}
113+
}),
114+
);
115+
116+
// Explicitly listen only for real-time `file` updates.
117+
tokio::spawn(
118+
subscription_clone
119+
.files_stream()
120+
.for_each(|file| async move { println!("(b) file: {:?}", file) }),
121+
);
122+
123+
// Sleep for a minute. Now you can send messages to the channels
124+
// "my_channel" and "other_channel" and see them printed in the console.
125+
// You can use the publishing example or [PubNub console](https://www.pubnub.com/docs/console/)
126+
// to send messages.
127+
tokio::time::sleep(tokio::time::Duration::from_secs(15)).await;
128+
129+
// You can also cancel the subscription at any time.
130+
// subscription.unsubscribe();
131+
132+
println!("\nDisconnect from the real-time data stream");
133+
pubnub.disconnect();
134+
135+
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
136+
137+
println!("\nReconnect to the real-time data stream");
138+
pubnub.reconnect(None);
139+
140+
// Let event engine process unsubscribe request
141+
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
142+
143+
// If Subscription or Subscription will go out of scope they will unsubscribe.
144+
// drop(subscription);
145+
// drop(subscription_clone);
146+
147+
println!(
148+
"\nUnsubscribe from all data streams. To restore requires `subscription.subscribe(None)` call." );
149+
// Clean up before complete work with PubNub client instance.
150+
pubnub.unsubscribe_all();
151+
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
152+
153+
Ok(())
154+
}

0 commit comments

Comments
 (0)