For this tutorial, we will use timers. Since timers are an async feature, we need to enable it before usage.
Iced offers three mutually exclusive features for that. They need to be enabled before usage:
Depending on your choice, your must also add the dependency crate to your Cargo.toml file:
The tokio crate is very popular, and we will use it as an example. First, we enable tokio feature and add tokio crate.
The dependencies of Cargo.toml should look like this:
[dependencies]
iced = { version = "0.13.1", features = ["tokio"] }
tokio = { version = "1.44.2", features = ["time"] }We use time::every function to obtain Subscription<Instant> struct.
Then we map the struct to Subscription<Message> using Subscription::map method, and call our message to increment the counter.
use iced::{
Task,
time::{self, Duration},
widget::text,
};
fn main() -> iced::Result {
iced::application("My App", MyApp::update, MyApp::view)
.subscription(MyApp::subscription)
.run_with(MyApp::new)
}
#[derive(Debug, Clone)]
enum Message {
Update,
}
#[derive(Default)]
struct MyApp {
seconds: u32,
}
impl MyApp {
fn new() -> (Self, Task<Message>) {
(Self { seconds: 0 }, Task::none())
}
fn update(&mut self, message: Message) -> Task<Message> {
match message {
Message::Update => self.seconds += 1,
}
Task::none()
}
fn view(&self) -> iced::Element<Message> {
text(self.seconds).into()
}
fn subscription(&self) -> iced::Subscription<Message> {
time::every(Duration::from_secs(1)).map(|_| Message::Update)
}
}➡️ Next: Batch Subscriptions
📘 Back: Table of contents
