Skip to content

Instantly share code, notes, and snippets.

@Adrek
Forked from Klerith/debouncer.dart
Created February 7, 2021 13:18
Show Gist options
  • Save Adrek/b68ed9d43b2eccdf528d375d70d17490 to your computer and use it in GitHub Desktop.
Save Adrek/b68ed9d43b2eccdf528d375d70d17490 to your computer and use it in GitHub Desktop.
Dart: Debouncer
import 'dart:async';
// Creditos
// https://stackoverflow.com/a/52922130/7834829
class Debouncer<T> {
Debouncer({ this.duration, this.onValue });
final Duration duration;
void Function(T value) onValue;
T _value;
Timer _timer;
T get value => _value;
set value(T val) {
_value = val;
_timer?.cancel();
_timer = Timer(duration, () => onValue(_value));
}
}
// final debouncer = Debouncer<String>(duration: Duration(milliseconds: 500 ));
void getSugerenciasPorQuery( String busqueda, LatLng proximidad ) {
debouncer.value = '';
debouncer.onValue = ( value ) async {
final resultados = await this.getResultadosPorQuery(value, proximidad);
this._sugerenciasStreamController.add(resultados);
};
final timer = Timer.periodic(Duration(milliseconds: 200), (_) {
debouncer.value = busqueda;
});
Future.delayed(Duration(milliseconds: 201)).then((_) => timer.cancel());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment