BLoC search debounce

Viewed 696

I have a bloc (piece of code)

    ...
  Stream<SearchState> _mapSearchSuggestionsEvent(SearchSuggestionsEvent event) async* {
    final results = await _searchApi.getSuggestions(event.query);
    yield SearchStateShowSuggestions(results);
  }
    ...

and tried to debounce events to avoid excessive network calls

  @override
  Stream<Transition<SearchEvent, SearchState>> transformEvents(
      Stream<SearchEvent> events, TransitionFunction<SearchEvent, SearchState> transitionFn) {
    return events.debounceTime(Duration(milliseconds: 1000)).asyncExpand(transitionFn);
  }

Also I added logs inside _searchApi.getSuggestions method.

What I see in logs :

I/flutter ( 4838):  [SearchApi] : getSuggestions
I/flutter ( 4838):  [SearchApi] : getSuggestions k
I/flutter ( 4838):  [SearchApi] : getSuggestions kr
I/flutter ( 4838):  [SearchApi] : getSuggestions kre
I/flutter ( 4838):  [SearchApi] : getSuggestions krev
I/flutter ( 4838):  [SearchApi] : getSuggestions kreve

and so on...

Adding event :

_textEditingController.addListener(() {
      _bloc.add(SearchSuggestionsEvent(_textEditingController.text));
    });

Maybe I don't understand, but why my calls is not skipping when I'm using debounce?

1 Answers

This is a code example from the official documentation:

@override
Stream<Transition<PostEvent, PostState>> transformEvents(
  Stream<PostEvent> events,
  TransitionFunction<PostEvent, PostState> transitionFn,
) {
  return super.transformEvents(
    events.debounceTime(const Duration(milliseconds: 500)),
    transitionFn,
  );
}

Please, double-check if that works in your case. Not sure, but maybe asyncExpand just delays your events but they are not skipped, meaning you still send a request for each input change. Source: https://bloclibrary.dev/#/flutterinfinitelisttutorial

Related