1use discard::DiscardOnDrop;
2use futures_signals::{
3	signal::{Signal, SignalExt},
4	signal_map::{MapDiff, SignalMap, SignalMapExt},
5	signal_vec::{SignalVec, SignalVecExt, VecDiff},
6	CancelableFutureHandle,
7};
8use wasm_bindgen_futures::spawn_local as spawn;
9
10pub trait SignalExt2: Signal {
11	fn subscribe<F>(self, callback: F) -> DiscardOnDrop<CancelableFutureHandle> where
12		F: FnMut(Self::Item) + 'static,
13		Self: Sized;
14}
15
16impl<T: Signal + 'static> SignalExt2 for T {
17	fn subscribe<F>(self, mut callback: F) -> DiscardOnDrop<CancelableFutureHandle> where
18		F: FnMut(Self::Item) + 'static,
19		Self: Sized,
20	{
21		let (handle, fut) = futures_signals::cancelable_future(self.for_each(move |x| { callback(x); async move {} }), || {});
22		spawn(fut);
23		handle
24	}
25}
26
27pub trait SignalMapExt2: SignalMap {
28	fn subscribe<F>(self, callback: F) -> DiscardOnDrop<CancelableFutureHandle> where
29		F: FnMut(MapDiff<Self::Key, Self::Value>) + 'static,
30		Self: Sized;
31}
32
33impl<T: SignalMap + 'static> SignalMapExt2 for T {
34	fn subscribe<F>(self, mut callback: F) -> DiscardOnDrop<CancelableFutureHandle> where
35		F: FnMut(MapDiff<Self::Key, Self::Value>) + 'static,
36		Self: Sized,
37	{
38		let (handle, fut) = futures_signals::cancelable_future(self.for_each(move |x| { callback(x); async move {} }), || {});
39		spawn(fut);
40		handle
41	}
42}
43
44pub trait SignalVecExt2: SignalVec {
45	fn subscribe<F>(self, callback: F) -> DiscardOnDrop<CancelableFutureHandle> where
46		F: FnMut(VecDiff<Self::Item>) + 'static,
47		Self: Sized;
48}
49
50impl<T: SignalVec + 'static> SignalVecExt2 for T {
51	fn subscribe<F>(self, mut callback: F) -> DiscardOnDrop<CancelableFutureHandle> where
52		F: FnMut(VecDiff<Self::Item>) + 'static,
53		Self: Sized,
54	{
55		let (handle, fut) = futures_signals::cancelable_future(self.for_each(move |x| { callback(x); async move {} }), || {});
56		spawn(fut);
57		handle
58	}
59}