-
Notifications
You must be signed in to change notification settings - Fork 3
/
gist.dart
285 lines (244 loc) · 7.25 KB
/
gist.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/*
* Throttling and Debouncing in dart for https://pub.dev/packages/throttling
* https://gist.github.com/PlugFox/8630021e5c7ab9d27b74e86372f74c31
* https://dartpad.dev?id=8630021e5c7ab9d27b74e86372f74c31
* Matiunin Mikhail <plugfox@gmail.com>, 22 November 2023
*/
// ignore_for_file: avoid_print, cascade_invocations, unawaited_futures
import 'dart:async';
void main([List<String>? arguments]) => Future<void>(() async {
print('\n' '# Throttling');
await throttling();
print('\n' '# Debouncing');
await debouncing();
});
Future<void> throttling() async {
final thr = Throttling<void>(duration: const Duration(milliseconds: 200));
thr.throttle(() {
print(' * 1');
}); // print ' * 1'
await Future<void>.delayed(const Duration(milliseconds: 100));
thr.throttle(() {
print(' * 2');
});
await Future<void>.delayed(const Duration(milliseconds: 100));
thr.throttle(() {
print(' * 3');
}); // print ' * 3'
thr.close();
}
Future<void> debouncing() async {
final deb = Debouncing<void>(duration: const Duration(milliseconds: 200));
deb.debounce(() {
print(' * 1');
});
await Future<void>.delayed(const Duration(milliseconds: 100));
deb.debounce(() {
print(' * 2');
});
await Future<void>.delayed(const Duration(milliseconds: 100));
deb.debounce(() {
print(' * 3');
});
await Future<void>.delayed(const Duration(milliseconds: 200));
// print ' * 3'
deb.close();
}
/* LIBRARY */
/// Throttling status
enum ThrottlingStatus {
/// Ready to accept new events
idle,
/// Waiting for the end of the pause
busy;
const ThrottlingStatus();
/// Ready to accept new events
bool get isIdle => this == ThrottlingStatus.idle;
/// Waiting for the end of the pause
bool get isBusy => this == ThrottlingStatus.busy;
@override
String toString() => switch (this) {
ThrottlingStatus.idle => 'idle',
ThrottlingStatus.busy => 'busy',
};
}
/// Debouncing status
enum DebouncingStatus {
/// Ready to accept new events
idle,
/// Waiting for the end of the pause
busy;
const DebouncingStatus();
/// Ready to accept new events
bool get isIdle => this == DebouncingStatus.idle;
/// Waiting for the end of the pause
bool get isBusy => this == DebouncingStatus.busy;
@override
String toString() => switch (this) {
DebouncingStatus.idle => 'idle',
DebouncingStatus.busy => 'busy',
};
}
/// Throttling
/// Have method [throttle]
final class Throttling<T> extends Stream<ThrottlingStatus>
implements Sink<T Function()> {
/// Throttling
/// Have method [throttle]
/// Must be closed with [close] method
Throttling({Duration duration = const Duration(seconds: 1)})
: assert(!duration.isNegative, 'Duration must be positive'),
_duration = duration {
_stateSC.sink.add(ThrottlingStatus.idle);
}
Duration _duration;
/// Get current duration
Duration get duration => _duration;
/// Set new duration
set duration(Duration value) {
assert(!duration.isNegative, 'Duration must be positive');
_duration = value;
}
/// {@nodoc}
Timer? _timer;
/// Is ready to accept new events
bool get isIdle => switch (_timer?.isActive) {
true => false,
_ => true,
};
/// Waiting for the end of the pause
bool get isBusy => !isIdle;
/// {@nodoc}
final StreamController<ThrottlingStatus> _stateSC =
StreamController<ThrottlingStatus>.broadcast(sync: true);
/// Limits the maximum number of times a given
/// event handler can be called over time.
///
/// Returns the result of the function.
/// If the function is not ready to accept new events,
/// it returns null.
T? throttle(T Function() func) {
if (_stateSC.isClosed || !isIdle) return null;
_timer = Timer(_duration, () {
_timer = null;
if (_stateSC.isClosed) return;
_stateSC.sink.add(ThrottlingStatus.idle);
});
_stateSC.sink.add(ThrottlingStatus.busy);
try {
return func();
} on Object {
rethrow;
}
}
@override
StreamSubscription<ThrottlingStatus> listen(
void Function(ThrottlingStatus status)? onData, {
Function? onError,
void Function()? onDone,
bool? cancelOnError,
}) =>
_stateSC.stream.listen(
onData,
onError: onError,
onDone: onDone,
cancelOnError: cancelOnError,
);
/// Shortcut for [throttle] method
@override
T? add(T Function() data) => throttle(data);
@override
void close() {
_timer?.cancel();
_timer = null;
_stateSC.close().ignore();
}
}
/// Debouncing
/// Have method [debounce]
final class Debouncing<T> extends Stream<DebouncingStatus>
implements Sink<T Function()> {
/// Debouncing
/// Have method [debounce]
/// Must be closed with [close] method
Debouncing({Duration duration = const Duration(seconds: 1)})
: assert(!duration.isNegative, 'Duration must be positive'),
_duration = duration {
_stateSC.sink.add(DebouncingStatus.idle);
}
Duration _duration;
/// Get current duration
Duration get duration => _duration;
/// Set new duration
set duration(Duration value) {
assert(!duration.isNegative, 'Duration must be positive');
_duration = value;
}
/// {@nodoc}
Timer? _timer;
/// {@nodoc}
Completer<T?>? _completer;
/// Is ready to accept new events
bool get isIdle => switch (_timer?.isActive) {
true => false,
_ => true,
};
/// Waiting for the end of the pause
bool get isBusy => !isIdle;
// ignore: close_sinks
final StreamController<DebouncingStatus> _stateSC =
StreamController<DebouncingStatus>.broadcast(sync: true);
/// Allows you to control events being triggered successively and,
/// if the interval between two sequential occurrences is less than
/// a certain amount of time (e.g. one second),
/// it completely ignores the first one.
Future<T?> debounce(T Function() func) async {
if (_stateSC.isClosed) return null;
if (isIdle) _stateSC.sink.add(DebouncingStatus.busy);
final completer = _completer ??= Completer<T?>();
_timer?.cancel();
_timer = Timer(_duration, () {
_completer = null;
_timer = null;
try {
final result = func();
completer.complete(result);
} on Object catch (error, stackTrace) {
completer.completeError(error, stackTrace); // coverage:ignore-line
} finally {
if (!_stateSC.isClosed) _stateSC.sink.add(DebouncingStatus.idle);
}
});
return completer.future;
}
@override
StreamSubscription<DebouncingStatus> listen(
void Function(DebouncingStatus status)? onData, {
Function? onError,
void Function()? onDone,
bool? cancelOnError,
}) =>
_stateSC.stream.listen(
onData,
onError: onError,
onDone: onDone,
cancelOnError: cancelOnError,
);
/// Shortcut for [debounce] method
@override
Future<T?> add(T Function() data) => debounce(data);
/// Free resources
/// If [force] is true, then the current event will be canceled.
@override
void close({bool force = false}) {
// coverage:ignore-start
if (force) {
_timer?.cancel();
_completer?.completeError(StateError('closed'));
_timer = null;
_completer = null;
}
// coverage:ignore-end
_stateSC.close().ignore();
}
}