Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
nullchinchilla committed Nov 4, 2024
1 parent 09d89d5 commit 0d42f35
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions binaries/geph5-client/src/refresh_cell.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use std::{future::Future, sync::Arc, time::Duration};

use parking_lot::Mutex;
use smolscale::immortal::Immortal;

pub struct RefreshCell<T: Clone> {
inner: Arc<Mutex<T>>,
_task: Immortal,
}

impl<T: Clone + Send + 'static> RefreshCell<T> {
pub async fn create<Fut: Future<Output = T> + Send>(
interval: Duration,
refresh: impl Fn() -> Fut + Send + 'static,
) -> Self {
let inner = Arc::new(Mutex::new(refresh().await));
let inner2 = inner.clone();
let task = Immortal::spawn(async move {
loop {
smol::Timer::after(interval).await;
let new_value = refresh().await;
let mut inner = inner2.lock();
*inner = new_value;
}
});
Self { inner, _task: task }
}

pub fn get(&self) -> T {
self.inner.lock().clone()
}
}

0 comments on commit 0d42f35

Please sign in to comment.