Skip to content

Commit f67c51d

Browse files
committed
feat: add a side_effect waiter which takes a function
And call that function every tick.
1 parent a1cd03d commit f67c51d

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

delay/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "delay"
3-
version = "0.2.0"
3+
version = "0.3.0"
44
authors = ["Hans Larsen <[email protected]>"]
55
edition = "2018"
66
description = "A collection of trait and classes to make your thread wait (and timeout)."

delay/src/lib.rs

+40
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,15 @@ impl Delay {
9696
Self::exponential_backoff_capped(initial, multiplier, Duration::from_secs(std::u64::MAX))
9797
}
9898

99+
/// Call a function every tick, expecting some kind of side effect (e.g. a progress
100+
/// bar).
101+
pub fn side_effect<F>(function: F) -> Self
102+
where
103+
F: 'static + Sync + Send + Clone + Fn() -> Result<(), WaiterError>,
104+
{
105+
Self::from(Box::new(SideEffectWaiter::new(function)))
106+
}
107+
99108
pub fn builder() -> DelayBuilder {
100109
DelayBuilder { inner: None }
101110
}
@@ -142,6 +151,12 @@ impl DelayBuilder {
142151
) -> Self {
143152
self.with(Delay::exponential_backoff_capped(initial, multiplier, cap))
144153
}
154+
pub fn side_effect<F>(self, function: F) -> Self
155+
where
156+
F: 'static + Sync + Send + Clone + Fn() -> Result<(), WaiterError>,
157+
{
158+
self.with(Delay::side_effect(function))
159+
}
145160
pub fn build(mut self) -> Delay {
146161
self.inner.take().unwrap_or_else(Delay::instant)
147162
}
@@ -289,3 +304,28 @@ impl Waiter for ExponentialBackoffWaiter {
289304
Ok(())
290305
}
291306
}
307+
308+
#[derive(Clone)]
309+
struct SideEffectWaiter<F>
310+
where
311+
F: 'static + Sync + Send + Clone + Fn() -> Result<(), WaiterError>,
312+
{
313+
function: F,
314+
}
315+
316+
impl<F> SideEffectWaiter<F>
317+
where
318+
F: 'static + Sync + Send + Clone + Fn() -> Result<(), WaiterError>,
319+
{
320+
pub fn new(function: F) -> Self {
321+
Self { function }
322+
}
323+
}
324+
impl<F> Waiter for SideEffectWaiter<F>
325+
where
326+
F: 'static + Sync + Send + Clone + Fn() -> Result<(), WaiterError>,
327+
{
328+
fn wait(&self) -> Result<(), WaiterError> {
329+
(self.function)()
330+
}
331+
}

0 commit comments

Comments
 (0)