-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
09d89d5
commit 0d42f35
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} | ||
} |