pub fn tick<F>(duration: Duration, f: F) -> CmdExpand description
Creates a command that produces a single message after a delay.
This command will send a message produced by the provided closure f
after the specified duration. Unlike every(), this produces only
one message and then completes. It’s commonly used for one-shot timers
that can be re-armed in the update method.
Note: Due to tokio’s interval implementation, the first tick is consumed to ensure the message is sent after a full duration, not immediately.
§Arguments
duration- The duration to wait before sending the messagef- A closure that takes aDurationand returns aMsg
§Returns
A command that will produce a single message after the specified duration
§Examples
use bubbletea_rs::{command, Model, Msg};
use std::time::Duration;
#[derive(Debug)]
struct TickMsg;
struct MyModel {
counter: u32,
}
impl Model for MyModel {
fn init() -> (Self, Option<command::Cmd>) {
let model = Self { counter: 0 };
// Start a timer that fires after 1 second
let cmd = command::tick(Duration::from_secs(1), |_| {
Box::new(TickMsg) as Msg
});
(model, Some(cmd))
}
fn update(&mut self, msg: Msg) -> Option<command::Cmd> {
if msg.downcast_ref::<TickMsg>().is_some() {
self.counter += 1;
// Re-arm the timer for another tick
return Some(command::tick(Duration::from_secs(1), |_| {
Box::new(TickMsg) as Msg
}));
}
None
}
fn view(&self) -> String {
format!("Counter: {}", self.counter)
}
}