Skip to content

Latest commit

 

History

History
78 lines (62 loc) · 2.6 KB

producing_messages_by_timers.md

File metadata and controls

78 lines (62 loc) · 2.6 KB

Producing Messages By Timers

To use build-in timers, we need to enable one of the following features: tokio, async-std, or smol. In this tutorial, we use tokio feature. The dependencies of Cargo.toml should look like this:

[dependencies]
iced = { version = "0.13.1", features = ["tokio"] }

We use time::every function to obtain Subscription<Instant> struct. Then we map the struct to Subscription<MyAppMessage> by Subscription::map method. The result will be returned in the subscription method of Application. The corresponding MyAppMessage will be received in the update method.

use iced::{
    time::{self, Duration},
    widget::text,
    Element, Subscription, Task,
};

fn main() -> iced::Result {
    iced::application(
        "producing messages by timers",
        MyApp::update,
        MyApp::view,
    )
    .subscription(MyApp::subscription)
    .run()
}

struct MyApp {
    seconds: u32,
}

impl Default for MyApp {
    fn default() -> Self {
        MyApp::new()
    }
}


#[derive(Debug, Clone)]
enum Message {
    Update,
}

impl MyApp {
    fn new() -> Self {
        Self { seconds: 0u32 }
    }

    fn update(&mut self, message: Message) -> Task<Message> {
        match message {
            Message::Update => {
                self.seconds += 1;
                return Task::none();
            }
        }
    }

    fn view(&self) -> Element<Message> {
        text(self.seconds).into()
    }

    fn subscription(&self) -> Subscription<Message> {
        time::every(Duration::from_secs(1)).map(|_| Message::Update)
    }
}

Producing messages by timers

➡️ Next: Batch Subscriptions

📘 Back: Table of contents