Skip to content

Commit f49bd64

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

File tree

3 files changed

+22
-9
lines changed

3 files changed

+22
-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: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ version.workspace = true
99
futures = "0.3"
1010
futures-channel = "0.3"
1111
futures-util = "0.3"
12+
libc = "0.2"
1213
glib.workspace = true
1314
gio.workspace = true
1415

examples/gio_futures_await/main.rs

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,41 @@
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);
26-
27-
l.run();
22+
let _ = c
23+
.block_on(c.spawn_local(gio::CancellableFuture::new(
24+
futures_util::future::join(
25+
future,
26+
clone!(
27+
#[strong]
28+
cancellable,
29+
async move {
30+
glib::unix_signal_future(libc::SIGINT).await;
31+
eprintln!("Ctrl+C pressed, operation will be stopped!");
32+
cancellable.cancel();
33+
}
34+
),
35+
),
36+
cancellable,
37+
)))
38+
.expect("futures must be executed");
2839
}
2940

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

0 commit comments

Comments
 (0)