@@ -10,6 +10,7 @@ use serde_json::Value;
10
10
use std:: error:: Error ;
11
11
use std:: hash:: { Hash , Hasher } ;
12
12
use std:: sync:: Arc ;
13
+ use tokio:: signal;
13
14
use tokio:: sync:: Mutex ;
14
15
use tokio:: task;
15
16
use tokio:: time:: { sleep, Duration } ;
@@ -163,6 +164,11 @@ async fn main() -> Result<(), Box<dyn Error>> {
163
164
let raw_client = iot_core_client. get_client ( ) . await ;
164
165
let client = Arc :: new ( Mutex :: new ( raw_client) ) ;
165
166
167
+ let shutdown_signal = async {
168
+ signal:: ctrl_c ( ) . await . expect ( "Failed to listen for Ctrl+C" ) ;
169
+ debug ! ( "Received shutdown signal, cleaning up..." ) ;
170
+ } ;
171
+
166
172
match args. command {
167
173
Some ( CliCommand :: Sub {
168
174
topics,
@@ -185,7 +191,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
185
191
let include_regex = include. map ( |s| Regex :: new ( & s) . unwrap ( ) ) ;
186
192
let exclude_regex = exclude. map ( |s| Regex :: new ( & s) . unwrap ( ) ) ;
187
193
188
- for topic in topic_list {
194
+ for topic in topic_list. clone ( ) {
189
195
client
190
196
. lock ( )
191
197
. await
@@ -230,11 +236,17 @@ async fn main() -> Result<(), Box<dyn Error>> {
230
236
. unwrap ( ) ;
231
237
} ) ;
232
238
233
- let ( recv_result, listen_result) = tokio:: join!( recv_thread, listen_thread) ;
234
-
235
- // Propagate errors if any
236
- recv_result?;
237
- listen_result?;
239
+ // Wait for either the threads to complete or the shutdown signal
240
+ tokio:: select! {
241
+ _ = recv_thread => { }
242
+ _ = listen_thread => { }
243
+ _ = shutdown_signal => {
244
+ for topic in topic_list. clone( ) {
245
+ client. lock( ) . await . unsubscribe( topic) . await ?;
246
+ println!( "{}" , format!( "Unsubscribed from topic: {}" , topic) . blue( ) ) ;
247
+ }
248
+ }
249
+ }
238
250
}
239
251
240
252
Some ( CliCommand :: Pub { topics, message } ) => {
0 commit comments