delayLoading method
Delays Loading states while letting other states through immediately.
Non-Loading states always pass through immediately. When a Loading state arrives, a timer starts. If a non-Loading state arrives before the timer fires, the pending Loading is cancelled and the non-Loading state is emitted — preventing flickering spinners on fast requests.
Example:
stream.delayLoading(Duration(milliseconds: 300))
Implementation
Stream<QoraState<T>> delayLoading(Duration duration) {
return transform(
StreamTransformer<QoraState<T>, QoraState<T>>(
(input, cancelOnError) {
final controller = StreamController<QoraState<T>>();
Timer? loadingTimer;
StreamSubscription<QoraState<T>>? inputSubscription;
inputSubscription = input.listen(
(state) {
if (state is Loading) {
loadingTimer ??= Timer(duration, () {
loadingTimer = null;
controller.add(state);
});
} else {
loadingTimer?.cancel();
loadingTimer = null;
controller.add(state);
}
},
onDone: () {
loadingTimer?.cancel();
controller.close();
},
onError: (Object e, StackTrace st) {
loadingTimer?.cancel();
controller.addError(e, st);
},
cancelOnError: cancelOnError,
);
controller.onCancel = () {
loadingTimer?.cancel();
inputSubscription?.cancel();
};
return controller.stream.listen(null);
},
),
);
}