Skip to content

Instantly share code, notes, and snippets.

@trizist
Forked from cetra3/store.rs
Created July 2, 2025 23:41
Show Gist options
  • Save trizist/315e70d2407c3cd6ff782d85597d23e2 to your computer and use it in GitHub Desktop.
Save trizist/315e70d2407c3cd6ff782d85597d23e2 to your computer and use it in GitHub Desktop.

Revisions

  1. @cetra3 cetra3 created this gist Aug 11, 2019.
    50 changes: 50 additions & 0 deletions store.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    use std::sync::RwLock;
    use std::sync::RwLockReadGuard;

    #[allow(dead_code)]
    pub struct Store<T, U> {
    name: String,
    state: RwLock<T>,
    listeners: RwLock<Vec<fn(&T, &U)>>,
    reducer: fn(&mut T, &U),
    }

    #[allow(dead_code)]
    impl<T, U> Store<T, U> {
    pub fn create_store<S: Into<String>>(
    name: S,
    reducer: fn(&mut T, &U),
    initial_state: T,
    ) -> Store<T, U> {
    Store {
    name: name.into(),
    state: RwLock::new(initial_state),
    listeners: RwLock::new(Vec::new()),
    reducer,
    }
    }

    pub fn subscribe(&self, listener: fn(&T, &U)) {
    let mut listeners = self.listeners.write().expect("Could not write subscriber");
    listeners.push(listener);
    }

    pub fn get_state(&self) -> RwLockReadGuard<T> {
    if let Err(_) = self.state.try_read() {
    warn!("Get State Called for `{}`, but would block", self.name);
    }

    self.state.read().expect("Could not get state")
    }

    pub fn dispatch(&self, action: U) {
    (self.reducer)(
    &mut self.state.write().expect("Could not write state"),
    &action,
    );

    for listener in &*self.listeners.read().expect("Could not notify listeners") {
    listener(&self.get_state(), &action)
    }
    }
    }