tauri_store/store/
watch.rs1use 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 id: WatcherId,
15 inner: Arc<WatcherFn<R>>,
16}
17
18impl<R: Runtime> Watcher<R> {
19 pub(crate) fn new<F>(f: F) -> (WatcherId, Self)
20 where
21 F: Fn(AppHandle<R>) -> Result<()> + Send + Sync + 'static,
22 {
23 let id = WatcherId(CURRENT_ID.fetch_add(1, Relaxed));
24 (id, Self { id, inner: Arc::new(f) })
25 }
26
27 pub(crate) fn call(&self, app: AppHandle<R>) {
28 let _ = (self.inner)(app);
29 }
30}
31
32impl<R: Runtime> Clone for Watcher<R> {
33 fn clone(&self) -> Self {
34 Self {
35 id: self.id,
36 inner: Arc::clone(&self.inner),
37 }
38 }
39}
40
41impl<R: Runtime> fmt::Debug for Watcher<R> {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 f.debug_struct("Listener")
44 .field("id", &self.id)
45 .finish_non_exhaustive()
46 }
47}
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
51pub struct WatcherId(u32);
52
53impl Deref for WatcherId {
54 type Target = u32;
55
56 fn deref(&self) -> &Self::Target {
57 &self.0
58 }
59}
60
61impl From<u32> for WatcherId {
62 fn from(id: u32) -> Self {
63 Self(id)
64 }
65}