This tutorial follows from the previous two tutorials (keyboard events and timers). We combine the two Subscriptions of keyboard events and timers. This is done by Subscription::batch function.
In the following app, press the space key to start or stop the timer.
use iced::{
event::{self, Status},
executor,
keyboard::{key::Named, Key},
time::{self, Duration},
widget::text,
Application, Command, Event, Settings, Subscription,
};
fn main() -> iced::Result {
MyApp::run(Settings::default())
}
#[derive(Debug, Clone)]
enum MyAppMessage {
StartOrStop,
Update,
}
struct MyApp {
seconds: u32,
running: bool,
}
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,
running: false,
},
Command::none(),
)
}
fn title(&self) -> String {
String::from("My App")
}
fn update(&mut self, message: Self::Message) -> iced::Command<Self::Message> {
match message {
MyAppMessage::StartOrStop => self.running = !self.running,
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> {
let subscr_key = event::listen_with(|event, status| match (event, status) {
(
Event::Keyboard(iced::keyboard::Event::KeyPressed {
key: Key::Named(Named::Space),
..
}),
Status::Ignored,
) => Some(MyAppMessage::StartOrStop),
_ => None,
});
if self.running {
Subscription::batch(vec![
subscr_key,
time::every(Duration::from_secs(1)).map(|_| MyAppMessage::Update),
])
} else {
subscr_key
}
}
}
➡️ Next: Drawing Shapes
📘 Back: Table of contents