tauri_store/store/
watch.rs

1use crate::error::Result;
2use std::fmt;
3use std::ops::Deref;
4use std::sync::atomic::AtomicU32;
5use std::sync::atomic::Ordering::Relaxed;
6use std::sync::Arc;
7use tauri::{AppHandle, Runtime};
8
9static CURRENT_ID: AtomicU32 = AtomicU32::new(0);
10
11type WatcherFn<R> = dyn Fn(AppHandle<R>) -> Result<()> + Send + Sync;
12
13pub(crate) struct Watcher<R: Runtime> {
14  pub(crate) id: WatcherId,
15  inner: Arc<WatcherFn<R>>,
16}
17
18impl<R: Runtime> Watcher<R> {
19  pub fn new<F>(f: F) -> Self
20  where
21    F: Fn(AppHandle<R>) -> Result<()> + Send + Sync + 'static,
22  {
23    Self {
24      id: WatcherId(CURRENT_ID.fetch_add(1, Relaxed)),
25      inner: Arc::new(f),
26    }
27  }
28
29  pub fn call(&self, app: AppHandle<R>) {
30    let _ = (self.inner)(app);
31  }
32}
33
34impl<R: Runtime> Clone for Watcher<R> {
35  fn clone(&self) -> Self {
36    Self {
37      id: self.id,
38      inner: Arc::clone(&self.inner),
39    }
40  }
41}
42
43impl<R: Runtime> fmt::Debug for Watcher<R> {
44  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45    f.debug_struct("Listener")
46      .field("id", &self.id)
47      .finish_non_exhaustive()
48  }
49}
50
51/// Unique watcher identifier.
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub struct WatcherId(u32);
54
55impl Deref for WatcherId {
56  type Target = u32;
57
58  fn deref(&self) -> &Self::Target {
59    &self.0
60  }
61}
62
63impl From<u32> for WatcherId {
64  fn from(id: u32) -> Self {
65    Self(id)
66  }
67}