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.12.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::{
executor,
time::{self, Duration},
widget::text,
Application, Command, Settings,
};
fn main() -> iced::Result {
MyApp::run(Settings::default())
}
#[derive(Debug, Clone)]
enum MyAppMessage {
Update,
}
struct MyApp {
seconds: u32,
}
impl Application for MyApp {
type Executor = executor::Default;
type Message = MyAppMessage;
type Theme = iced::Theme;
type Flags = ();
fn new(_flags: Self::Flags) -> (Self, iced::Command<Self::Message>) {
(Self { seconds: 0 }, Command::none())
}
fn title(&self) -> String {
String::from("My App")
}
fn update(&mut self, message: Self::Message) -> iced::Command<Self::Message> {
match message {
MyAppMessage::Update => self.seconds += 1,
}
Command::none()
}
fn view(&self) -> iced::Element<Self::Message> {
text(self.seconds).into()
}
fn subscription(&self) -> iced::Subscription<Self::Message> {
time::every(Duration::from_secs(1)).map(|_| MyAppMessage::Update)
}
}
➡️ Next: Batch Subscriptions
📘 Back: Table of contents