nami/
ext.rs

1use crate::{Computed, Signal, cache::Cached, map::Map, signal::WithMetadata, zip::Zip};
2
3#[cfg(feature = "timer")]
4use crate::debounce::Debounce;
5#[cfg(feature = "timer")]
6use core::time::Duration;
7
8/// Extension trait providing convenient methods for all Signal types.
9///
10/// This trait adds utility methods to any type implementing Signal,
11/// allowing for easy chaining of operations like mapping, zipping, and caching.
12pub trait SignalExt: Signal + Sized {
13    /// Transforms the output of this signal using the provided function.
14    fn map<F, Output>(self, f: F) -> Map<Self, F, Output>
15    where
16        F: 'static + Clone + Fn(Self::Output) -> Output,
17        Output: 'static,
18        Self: 'static,
19    {
20        Map::new(self, f)
21    }
22
23    /// Combines this signal with another signal into a tuple.
24    fn zip<B>(self, b: B) -> Zip<Self, B>
25    where
26        B: Signal,
27        Self::Output: Clone,
28        B::Output: Clone,
29    {
30        Zip::new(self, b)
31    }
32
33    /// Wraps this signal with caching to avoid redundant computations.
34    fn cached(self) -> Cached<Self>
35    where
36        Self::Output: Clone,
37    {
38        Cached::new(self)
39    }
40
41    /// Converts this signal into a type-erased `Computed` container.
42    fn computed(self) -> Computed<Self::Output>
43    where
44        Self: 'static,
45    {
46        Computed::new(self)
47    }
48
49    /// Attaches metadata to this signal's watcher notifications.
50    fn with<T>(self, metadata: T) -> WithMetadata<Self, T> {
51        WithMetadata::new(metadata, self)
52    }
53
54    #[cfg(feature = "timer")]
55    /// Creates a debounced version of this signal.
56    ///
57    /// The debounced signal will only emit values after the specified duration
58    /// has passed without receiving new values.
59    fn debounce(self, duration: Duration) -> Debounce<Self, executor_core::DefaultExecutor>
60    where
61        Self::Output: Clone,
62    {
63        Debounce::new(self, duration)
64    }
65    #[cfg(feature = "timer")]
66    /// Creates a throttled version of this signal.
67    ///
68    /// The throttled signal will emit values at most once every specified duration,
69    /// ignoring any additional values received during that period.
70    fn throttle(
71        self,
72        duration: Duration,
73    ) -> crate::throttle::Throttle<Self, executor_core::DefaultExecutor>
74    where
75        Self::Output: Clone,
76    {
77        crate::throttle::Throttle::new(self, duration)
78    }
79}
80
81impl<C: Signal + Sized> SignalExt for C {}