Recipes
Debounce modes and maxWait
Respond to the first change, process the latest after quiet, and bound continuous input without changing execution rules.
An editor may need a preview as soon as typing begins, another update while typing continues, and a final update when the user pauses. Waiting only for silence can postpone the preview indefinitely. Running every change may do unnecessary work.
Core 1.5.0 adds two choices alongside the existing trailing debounce. This recipe processes revision numbers locally; it does not implement reliable autosave, network retries, or offline storage.
Choose what passes the filter
| Mode | What passes |
|---|---|
trailing — default | Only the latest candidate after a quiet period |
leading | The first entry immediately; subsequent entries are suppressed until quiet |
leadingAndTrailing | The first immediately, then the latest subsequent candidate after quiet |
A single entry in leadingAndTrailing passes once, not a second time at the end of the window. Events share a series only when both the exact Command type and executionKey match.
For A at 0 ms, B at 60 ms, C at 130 ms and a 100 ms quiet period:
- trailing passes C at 230 ms;
- leading passes A immediately and suppresses B/C;
- leadingAndTrailing passes A immediately and C at 230 ms;
- leadingAndTrailing throttle instead passes A at 0, B at 100, C at 130 ms: its window is fixed rather than extended by input.
These times describe the input filter, not a guaranteed handler start.
Run the complete example
In a Dart console project, install core and place the following file in bin/debounce_demo.dart:
dart pub add usecase_forge:^1.5.0
import 'dart:async';
import 'package:usecase_forge/usecase_forge.dart';
Future<void> main() async {
final _DraftUseCase useCase = _DraftUseCase();
final Stopwatch elapsed = Stopwatch()..start();
final StreamSubscription<UseCaseSnapshot<int>> subscription = useCase.stream
.where((final UseCaseSnapshot<int> snapshot) =>
snapshot.phase == UseCaseExecutionPhase.finished)
.listen((final UseCaseSnapshot<int> snapshot) => print(
'${elapsed.elapsedMilliseconds} ms: processed revision ${snapshot.state}'));
try {
for (int revision = 1; revision <= 12; revision++) {
useCase.add(_DraftChanged(revision));
await Future<void>.delayed(const Duration(milliseconds: 40));
}
await Future<void>.delayed(const Duration(milliseconds: 160));
} finally {
await useCase.close();
await subscription.cancel();
elapsed.stop();
}
}
final class _DraftChanged extends UseCaseCommand {
const _DraftChanged(this.revision);
final int revision;
@override
Object get executionKey => 'current-document';
}
final class _DraftUseCase extends UseCase<int> {
_DraftUseCase() : super(initialState: 0) {
registerCommand<_DraftChanged>(_process);
}
@override
UseCaseInstructions get defaultInstructions => UseCaseInstructions(
input: UseCaseInputInstructions(
conflictPolicy: UseCaseInputConflictPolicy.replace,
debounce: UseCaseDebounceInstructions(
duration: const Duration(milliseconds: 100),
mode: UseCaseDebounceMode.leadingAndTrailing,
maxWait: const Duration(milliseconds: 250),
),
),
processing: const UseCaseProcessingInstructions(
executionMode: UseCaseExecutionMode.sequential,
),
);
Future<void> _process(final _DraftChanged command,
final UseCaseExecutionContext<int> context) async =>
context.publish(command.revision);
}
dart run bin/debounce_demo.dart
The first revision is processed immediately. During continuous input, maxWait lets the latest candidate advance after 250 ms. When input stops, the last unprocessed candidate passes after 100 ms of quiet. Exact timestamps and the intermediate revision depend on actual timer delivery; do not test a fixed console transcript.
The delays above simulate the producer's keystrokes. They are not a second debounce timer around add. The UseCase owns that timer. This example has one active document; use an actual document ID as the key when grouping several documents.
Understand maxWait and replace
Without maxWait, events at 0/60/120/180/240 ms postpone trailing output to 340 ms. With maxWait: 250 ms, the last candidate advances at 250 ms. If input continues, another maximum interval starts from that release; leading does not fire again until a genuine quiet period ends the series.
MaxWait must be at least duration and cannot be used with pure leading, which has no trailing candidate. Invalid combinations throw ArgumentError.
With a new mode or a non-null maxWait, input replace removes the old Entry but preserves the series. Replacing each draft cannot reset its maximum deadline. Removed entries receive replaced, not debounced. The old duration-only configuration keeps its original reset behavior, including explicit mode: trailing, maxWait: null.
Keep execution and persistence separate
MaxWait bounds only waiting inside debounce. Pending capacity, awaited hooks, processingLimit, sequential lanes, later throttle/rate limit, and I/O can delay or reject further work. Admission capacity is checked before debounce replaces a candidate; rejected inputs do not extend the series.
Sequential still waits for Starting/Processing in its group. Restart cancels matching work only when a candidate reaches processing, not when new input arrives. Close cancels pending timers without flushing a final save. Handler failures are not automatically retried.
A suspended browser tab can delay timer delivery; maxWait is not a wall-clock guarantee in that environment.
Use controlled time to test these boundaries; the existing Test companion needs no API update. Use the latest-search recipe when the requirement is trailing search plus restart. In DevTools, version 1.3.0 labels mode, quiet duration and maxWait for core 1.5.0 entries and resolved registrations.