-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
main.rs
53 lines (40 loc) · 1.33 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use std::future::pending;
use std::thread;
use std::time::Duration;
use gio::prelude::*;
use futures::prelude::*;
/// A very long task. This task actually never ends.
async fn a_very_long_task() {
println!("Very long task started");
pending().await
}
fn main() {
const TIMEOUT: Duration = Duration::from_secs(3);
let main_ctx = glib::MainContext::default();
let main_loop = glib::MainLoop::new(Some(&main_ctx), false);
let cancellable = gio::Cancellable::new();
{
let main_loop = main_loop.clone();
// We wrap `a_very_long_task` inside a `CancellableFuture` controlled by `cancellable`.
// The task is cancelled when `.cancel()` is invoked.
let cancellable_task = gio::CancellableFuture::new(a_very_long_task(), cancellable.clone())
.map(move |res| {
if let Err(error) = res {
println!("{error:?}");
}
main_loop.quit();
});
main_ctx.spawn_local(cancellable_task);
}
// We simulate a timeout here.
// After `TIMEOUT` we cancel the pending task.
thread::spawn(move || {
thread::sleep(TIMEOUT);
println!(
"Timeout ({:?}) elapsed! Cancelling pending task...",
TIMEOUT
);
cancellable.cancel();
});
main_loop.run();
}