Flutter - Transform flutter bloc event to add debounce
Solution 1:
I found the solution.
@override
Stream<Transition< GithubSearchEvent, GithubSearchState >> transformEvents(
Stream< GithubSearchEvent > events, transitionFn) {
return events
.debounceTime(const Duration(milliseconds: 300))
.switchMap((transitionFn));
}
Solution 2:
Since bloc
8.0.0 the syntax changed and you need to pass it as a transformer to the on
function. Apart from the debouncing you should think about concurrency. To combine sequential processing with a debounce, you can provide the following function:
import 'package:rxdart/rxdart.dart';
//...
on<GithubSearchEvent>(
(event, emit) {},
transformer: (events, mapper) {
return events.debounceTime(const Duration(milliseconds: 300)).asyncExpand(mapper);
},
);
You can create a reusable transformer as a top-level function like this:
EventTransformer<Event> debounceSequential<Event>(Duration duration) {
return (events, mapper) => events.debounceTime(duration).asyncExpand(mapper);
}
and use it like this:
on<GithubSearchEvent>(
(event, emit) {},
transformer: debounceSequential(const Duration(milliseconds: 300)),
);
Solution 3:
I cannt add comment to @user2220771 cause my reputation is too low.
This will not work:
EventTransformer<Event> debounceTransformer<Event>(Duration duration) {
return (events, mapper) => events.debounceTime(duration);
}
you have to switch map as:
EventTransformer<Event> debounceTransformer<Event>(Duration duration) {
return (events, mapper) {
return events.debounceTime(duration).switchMap(mapper);
};
}