Skip to content

Commit

Permalink
revision: debounce
Browse files Browse the repository at this point in the history
  • Loading branch information
DogeDark committed Apr 28, 2024
1 parent d9bb37c commit 9b14e40
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
7 changes: 5 additions & 2 deletions examples/timing/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,17 @@ fn app() -> Element {
count += 1;
});

let mut debounce = use_debounce(Duration::from_millis(2000), move || count.set(0));
let mut debounce = use_debounce(Duration::from_millis(2000), move |text| {
println!("{text}");
count.set(0);
});

rsx! {
p { "{count}" },
button {
onclick: move |_| {
// Reset the counter after 2 seconds pass since the last click.
debounce.action();
debounce.action("button was clicked");
},
"Reset the counter! (2 second debounce)"
}
Expand Down
22 changes: 11 additions & 11 deletions sdk/src/utils/timing/debounce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ use std::time::Duration;
///
/// See [`use_debounce`] for more information.
#[derive(Clone, Copy, PartialEq)]
pub struct UseDebounce {
sender: Signal<Sender<bool>>,
pub struct UseDebounce<T: 'static> {
sender: Signal<Sender<T>>,
}

impl UseDebounce {
impl<T> UseDebounce<T> {
/// Will start the debounce countdown, resetting it if already started.
pub fn action(&mut self) {
self.sender.write().unbounded_send(true).ok();
pub fn action(&mut self, data: T) {
self.sender.write().unbounded_send(data).ok();
}
}

Expand All @@ -33,19 +33,19 @@ impl UseDebounce {
/// use std::time::Duration;
///
/// fn App() -> Element {
/// let mut debounce = use_debounce(Duration::from_millis(2000), || println!("ran"));
/// let mut debounce = use_debounce(Duration::from_millis(2000), |_| println!("ran"));
///
/// rsx! {
/// button {
/// onclick: move |_| {
/// debounce.action();
/// debounce.action(());
/// },
/// "Click!"
/// }
/// }
/// }
/// ```
pub fn use_debounce(time: Duration, cb: impl FnOnce() + Copy + 'static) -> UseDebounce {
pub fn use_debounce<T: Copy>(time: Duration, cb: impl FnOnce(T) + Copy + 'static) -> UseDebounce<T> {
use_hook(|| {
let (sender, mut receiver) = mpsc::unbounded();
let debouncer = UseDebounce {
Expand All @@ -56,14 +56,14 @@ pub fn use_debounce(time: Duration, cb: impl FnOnce() + Copy + 'static) -> UseDe
let mut current_task: Option<Task> = None;

loop {
if receiver.next().await.is_some() {
if let Some(task) = current_task {
if let Some(data) = receiver.next().await {
if let Some(task) = current_task.take() {
task.cancel();
}

current_task = Some(spawn(async move {
tokio::time::sleep(time).await;
cb();
cb(data);
}));
}
}
Expand Down

0 comments on commit 9b14e40

Please sign in to comment.