~raph/crochet

ref: de6d9ecbca8cbd1197ac250ab429f77f93620368 crochet/examples/async.rs -rw-r--r-- 1.4 KiB
de6d9ecbRaph Levien Add data to use_future 1 year, 7 months ago
                                                                                
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
//! A very simple async example.

use druid::{AppLauncher, PlatformError, Widget, WindowDesc};

use crochet::{AppHolder, Button, Cx, DruidAppData, Label};

fn main() -> Result<(), PlatformError> {
    let main_window = WindowDesc::new(ui_builder);
    let data = Default::default();
    AppLauncher::with_window(main_window)
        .use_simple_logger()
        .launch(data)
}

#[derive(Default)]
struct MyAppLogic {
    count: usize,
}

impl MyAppLogic {
    fn run(&mut self, cx: &mut Cx) {
        Label::new(format!("current count: {}", self.count)).build(cx);
        if Button::new("Increment").build(cx) {
            self.count += 1;
        }
        if self.count > 3 && self.count < 6 {
            Label::new("You did it!").build(cx);
        }
        cx.use_future(
            self.count,
            |&val| async move {
                async_std::task::sleep(std::time::Duration::from_secs(1)).await;
                val * 2
            },
            |cx, result| {
                let text = if let Some(val) = result {
                    format!("value: {}", val)
                } else {
                    "waiting...".into()
                };
                Label::new(text).build(cx);
            },
        )
    }
}

fn ui_builder() -> impl Widget<DruidAppData> {
    let mut app_logic = MyAppLogic::default();

    AppHolder::new(move |cx| app_logic.run(cx))
}