Skip to content

Commit e0e3f01

Browse files
committed
examples/gio_futures_await: Add CancellableFuture example
Handle SIGINT via the unix signal future and cancellation via the CancellableFuture
1 parent 09d576e commit e0e3f01

File tree

3 files changed

+24
-9
lines changed

3 files changed

+24
-9
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ version.workspace = true
99
futures = "0.3"
1010
futures-channel = "0.3"
1111
futures-util = "0.3"
12-
glib.workspace = true
12+
libc = "0.2"
13+
glib = { workspace = true, features = ["futures"] }
1314
gio.workspace = true
1415

1516
[dependencies.async-tls]

examples/gio_futures_await/main.rs

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,43 @@
1-
use std::str;
2-
31
use futures::prelude::*;
42
use gio::prelude::*;
53
use glib::clone;
64

75
fn main() {
86
let c = glib::MainContext::default();
9-
let l = glib::MainLoop::new(Some(&c), false);
10-
117
let file = gio::File::for_path("Cargo.toml");
8+
let cancellable = gio::Cancellable::new();
129

1310
let future = clone!(
1411
#[strong]
15-
l,
12+
cancellable,
1613
async move {
1714
match read_file(file).await {
1815
Ok(()) => (),
1916
Err(err) => eprintln!("Got error: {err}"),
2017
}
21-
l.quit();
18+
cancellable.cancel();
2219
}
2320
);
2421

25-
c.spawn_local(future);
22+
#[cfg(unix)]
23+
let cancel_future = clone!(
24+
#[strong]
25+
cancellable,
26+
async move {
27+
glib::unix_signal_future(libc::SIGINT).await;
28+
eprintln!("Ctrl+C pressed, operation will be stopped!");
29+
cancellable.cancel();
30+
}
31+
);
32+
#[cfg(not(unix))]
33+
let cancel_future = async move {};
2634

27-
l.run();
35+
let _ = c
36+
.block_on(c.spawn_local(gio::CancellableFuture::new(
37+
futures_util::future::join(future, cancel_future),
38+
cancellable,
39+
)))
40+
.expect("futures must be executed");
2841
}
2942

3043
/// Throughout our chained futures, we convert all errors to strings

0 commit comments

Comments
 (0)