mobx.dart icon indicating copy to clipboard operation
mobx.dart copied to clipboard

Add a way to interrupt debounce

Open subzero911 opened this issue 3 years ago • 2 comments

I have a city navigation app, to search for interesting places. I have categories (parks, cinemas, nightclubs, etc.) and a search textfield. I enter the text and do a debounced search with reaction:

reaction((_) => store.searchText.value, (_) => _searchPlaces(query, category), delay: 500);

But what if I started typing and decided to change the category, and rapidly tapped to the another category chip? In this case, I changed the category, but a search for previous category still has been executed. I need a way to interrupt debounce. Consider providing some API like

reactionDisposer.cancelScheduledReaction();

subzero911 avatar Sep 30 '22 20:09 subzero911

@subzero911 I think _searchPlaces should handle that.

method 1. Shows only the results of the last request


DateTime _lastSearchTime;

Future<void> _searchPlaces() async {
  final searchTime = DateTIme.now();
  _lastSearchTime = searchTime;
  final result = await networkCall();
  if ( _lastSearchTime <= searchTime) {
    // show result
  }
};

method 2. cancel previous request

// use dio.
CancelToken? _token;
Future<void> _searchPlaces() {
  // Cancel if there is a previous request
  _token?.cancel('cancel');
  _token = CancelToken();
  dio.get(url, cancelToken: token)
     .catchError((DioError err){
      if (CancelToken.isCancel(err)) {
        print('Request canceled! '+ err.message)
      }else{
        // handle error.
      }
     });
};

amondnet avatar Oct 12 '22 04:10 amondnet

Well, this looks reasonable.

subzero911 avatar Oct 13 '22 08:10 subzero911