Skip to content

Commit 76acf24

Browse files
swsnrbilelmoussaoui
authored andcommitted
Demo async call handling for gdbus
1 parent 6992955 commit 76acf24

File tree

1 file changed

+31
-12
lines changed
  • examples/gio_dbus_register_object

1 file changed

+31
-12
lines changed

examples/gio_dbus_register_object/main.rs

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
use gio::{prelude::*, IOErrorEnum};
2-
use std::sync::mpsc::{channel, Receiver, Sender};
2+
use std::{
3+
sync::mpsc::{channel, Receiver, Sender},
4+
time::Duration,
5+
};
36

47
const EXAMPLE_XML: &str = r#"
58
<node>
@@ -8,6 +11,11 @@ const EXAMPLE_XML: &str = r#"
811
<arg type='s' name='name' direction='in'/>
912
<arg type='s' name='greet' direction='out'/>
1013
</method>
14+
<method name='SlowHello'>
15+
<arg type='s' name='name' direction='in'/>
16+
<arg type='u' name='delay' direction='in'/>
17+
<arg type='s' name='greet' direction='out'/>
18+
</method>
1119
</interface>
1220
</node>
1321
"#;
@@ -17,15 +25,23 @@ struct Hello {
1725
name: String,
1826
}
1927

28+
#[derive(Debug, glib::Variant)]
29+
struct SlowHello {
30+
name: String,
31+
delay: u32,
32+
}
33+
2034
#[derive(Debug)]
2135
enum Call {
2236
Hello(Hello),
37+
SlowHello(SlowHello),
2338
}
2439

2540
impl Call {
2641
pub fn parse(method: &str, parameters: glib::Variant) -> Result<Call, glib::Error> {
2742
match method {
2843
"Hello" => Ok(parameters.get::<Hello>().map(Call::Hello)),
44+
"SlowHello" => Ok(parameters.get::<SlowHello>().map(Call::SlowHello)),
2945
_ => Err(glib::Error::new(IOErrorEnum::Failed, "No such method")),
3046
}
3147
.and_then(|p| p.ok_or_else(|| glib::Error::new(IOErrorEnum::Failed, "Invalid parameters")))
@@ -42,21 +58,24 @@ fn on_startup(app: &gio::Application, tx: &Sender<gio::RegistrationId>) {
4258

4359
if let Ok(id) = connection
4460
.register_object("/com/github/gtk_rs/examples/HelloWorld", &example)
45-
.method_call(glib::clone!(
46-
#[strong]
47-
app,
48-
move |_, _, _, _, method, params, invocation| {
49-
let result = Call::parse(method, params).map(|call| match call {
61+
.method_call(move |_, _, _, _, method, params, invocation| {
62+
let call = Call::parse(method, params);
63+
invocation.return_future_local(async move {
64+
match call? {
5065
Call::Hello(Hello { name }) => {
5166
let greet = format!("Hello {name}!");
5267
println!("{greet}");
53-
Some(greet.to_variant())
68+
Ok(Some(greet.to_variant()))
69+
}
70+
Call::SlowHello(SlowHello { name, delay }) => {
71+
glib::timeout_future(Duration::from_secs(delay as u64)).await;
72+
let greet = format!("Hello {name} after {delay} seconds!");
73+
println!("{greet}");
74+
Ok(Some(greet.to_variant()))
5475
}
55-
});
56-
invocation.return_result(result);
57-
app.quit();
58-
}
59-
))
76+
}
77+
});
78+
})
6079
.build()
6180
{
6281
println!("Registered object");

0 commit comments

Comments
 (0)