Skip to content

Commit

Permalink
Simplify debouncer implementation (simple timer without streams)
Browse files Browse the repository at this point in the history
  • Loading branch information
bizz84 committed Apr 14, 2024
1 parent 2787287 commit 57a1156
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,26 @@ part 'movies_search_query_notifier.g.dart';
@riverpod
class MoviesSearchQueryNotifier extends _$MoviesSearchQueryNotifier {
/// Used to debounce the input queries
final _searchQueryController = StreamController<String>.broadcast();
Timer? _debounceTimer;
late final StreamSubscription<String> _subscription;

@override
String build() {
// Listen to the stream of input queries
_subscription = _searchQueryController.stream.listen((query) {
// Cancel existing timer if there is one
_debounceTimer?.cancel();
// Set a new timer to debounce the query
_debounceTimer = Timer(const Duration(milliseconds: 500), () {
_updateState(query);
});
});

// don't forget to close the StreamController and cancel the subscriptions on dispose
ref.onDispose(() {
_searchQueryController.close();
_subscription.cancel();
_debounceTimer?.cancel();
});

// by default, return an empty query
return '';
}

void _updateState(String query) {
// only update the state once the query has been debounced
state = query;
}

void setQuery(String query) {
_searchQueryController.sink.add(query);
// Cancel the timer if it is active
if (_debounceTimer != null) {
_debounceTimer!.cancel();
}
_debounceTimer = Timer(const Duration(milliseconds: 500), () {
// only update the state once the query has been debounced
state = query;
});
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 57a1156

Please sign in to comment.