mobx.dart
mobx.dart copied to clipboard
Add a way to interrupt debounce
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
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.
}
});
};
Well, this looks reasonable.