This commit is contained in:
2026-09-07 11:41:59 +01:00
parent bc5a26b728
commit 3490af52e4
12 changed files with 274 additions and 170 deletions
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "service-datatime"
version.workspace = true
edition.workspace = true
[lib]
name = "service_datatime"
path = "src/lib.rs"
[dependencies]
common = { path = "../../common" }
iced = { workspace = true }
tokio = { workspace = true }
chrono = { workspace = true }
+73
View File
@@ -0,0 +1,73 @@
//! Clock service: emits a `ServicePayloadKind` event whenever a clock kind's
//! displayed value changes (minute or second rollover).
//!
//! The ticker knows nothing about the app's `Message` type; it produces
//! protocol events from `common` that core routes to subscribed modules.
use std::collections::HashMap;
use iced::{futures::SinkExt, Subscription};
use common::{ClockKind, ClockPayload, ServicePayloadKind};
/// Emits a payload only when a kind's displayed value changes (minute or
/// second rollover). Drive `tick` once per second.
#[derive(Default)]
pub struct ClockTicker {
last: HashMap<ClockKind, String>,
}
impl ClockTicker {
pub fn new() -> Self {
Self::default()
}
/// Subscription that emits `ServicePayloadKind::Clock` on every change.
pub fn run() -> Subscription<ServicePayloadKind> {
Subscription::run_with((), |_| {
iced::stream::channel(
0,
|mut sender: iced::futures::channel::mpsc::Sender<ServicePayloadKind>| async move {
let mut clock = ClockTicker::new();
let mut interval = tokio::time::interval(std::time::Duration::from_secs(1));
loop {
interval.tick().await;
for payload in clock.tick() {
if sender
.send(ServicePayloadKind::Clock(payload))
.await
.is_err()
{
return;
}
}
}
},
)
})
}
/// Returns a payload per kind whose value changed since the last tick.
/// The second that rolls into a new minute yields `[Seconds, Mins]`.
pub fn tick(&mut self) -> Vec<ClockPayload> {
let now = chrono::Local::now();
[ClockKind::Seconds, ClockKind::Mins]
.into_iter()
.filter_map(|kind| {
let value = now
.format(match kind {
ClockKind::Mins => "%H:%M",
ClockKind::Seconds => "%H:%M:%S",
})
.to_string();
match self.last.get(&kind) {
Some(prev) if *prev == value => None,
_ => {
self.last.insert(kind, value.clone());
Some(ClockPayload { kind, value })
}
}
})
.collect()
}
}