-
Notifications
You must be signed in to change notification settings - Fork 68
/
timer.rs
62 lines (51 loc) · 1.53 KB
/
timer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use crux_core::capability::{CapabilityContext, Operation};
use futures::StreamExt;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum TimerOperation {
Start { id: u64, millis: usize },
Cancel { id: u64 },
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum TimerOutput {
Created { id: u64 },
Finished { id: u64 },
}
impl Operation for TimerOperation {
type Output = TimerOutput;
}
#[derive(crux_core::macros::Capability)]
pub struct Timer<Event> {
context: CapabilityContext<TimerOperation, Event>,
}
impl<Ev> Timer<Ev>
where
Ev: 'static,
{
pub fn new(context: CapabilityContext<TimerOperation, Ev>) -> Self {
Self { context }
}
pub fn start<F>(&self, id: u64, millis: usize, make_event: F)
where
F: FnOnce(TimerOutput) -> Ev + Clone + Send + 'static,
{
self.context.spawn({
let context = self.context.clone();
async move {
let mut stream = context.stream_from_shell(TimerOperation::Start { id, millis });
while let Some(output) = stream.next().await {
let make_event = make_event.clone();
context.update_app(make_event(output));
}
}
})
}
pub fn cancel(&self, id: u64) {
self.context.spawn({
let context = self.context.clone();
async move {
context.notify_shell(TimerOperation::Cancel { id }).await;
}
})
}
}