3

I'm still rather new to Rust and have a hard time wrapping my head around futures. I want to implement a "timer app" in the browser and to do so I'm using https://yew.rs/. For the timer I tried to use https://github.com/tomaka/wasm-timer/, but there are not docs and no examples. Looks like the usage is supposed to be obvious, but I don't get it.

I assume that I have to do something like:

let i = Interval::new(core::time::Duration::from_millis(250));

This should create an Interval that fires every 250ms. But what is fired? How to I specify my callback? I would expect something like:

i.somehow_specify_callback(|| { ... executed every 250ms ...});

My feeling is, that I'm somehow on the wrong path and do not get grasp Rust futures. A working example on how to make an Interval execute some code would be very appreciated.

Achim
  • 15,415
  • 15
  • 80
  • 144

1 Answers1

1

Here is a pseudo code example for Timer component:

enum SecondsStateAction {
    Increment,
}

#[derive(Default)]
struct SecondsState {
    seconds: usize,
}

impl Reducible for SecondsState {
    /// Reducer Action Type
    type Action = SecondsStateAction;

    /// Reducer Function
    fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
        match action {
            SecondsStateAction::Increment => Self { seconds: self.seconds + 1 }.into(),
        }
    }
}

#[function_component(Timer)]
pub fn timer() -> Html {
    let seconds_state_handle = use_reducer(SecondsState::default);

    use_effect_with_deps(
        {
            let seconds_state_handle = seconds_state_handle.clone();

            move |_| {
                // i intervals get out of scope they get dropped and destroyed
                let interval = Interval::new(1000, move || seconds_state_handle.dispatch(SecondsStateAction::Increment));

                // So we move it into the clean up function, rust will consider this still being used and wont drop it
                // then we just drop it ourselves in the cleanup 
                move || drop(interval)
            }
        },
        (), // Only create the interval once per your component existence
    );

    html! {<h1>{*seconds_state_handle}{" seconds has passed since this component got rendered"}</h1>}
}

to learn more about the hooks i used in the code visit https://yew.rs/docs/concepts/function-components/hooks#pre-defined-hooks

Iter Ator
  • 8,226
  • 20
  • 73
  • 164
Julius Lungys
  • 191
  • 1
  • 6