問題描述
Flutter ‑ 轉換顫振 bloc 事件以添加去抖動 (Flutter ‑ Transform flutter bloc event to add debounce)
我正在嘗試使用顫振 bloc 製作一個無限列表。
根據這篇文章,要在兩個事件之間添加延遲以便 api 不會被垃圾郵件發送,您需要覆蓋 transformEvents 並為這樣的事件添加去抖動:
@override
Stream<GithubSearchState> transformEvents(
Stream<GithubSearchEvent> events,
Stream<GithubSearchState> Function(GithubSearchEvent event) next,
) {
return (events as Observable<GithubSearchEvent>)
.debounceTime(
Duration(milliseconds: 300),
)
.switchMap(next);
}
我面臨的問題是 Observable 已被 RxDart 棄用,我不確定如何完成上述要求。
參考解法
方法 1:
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)),
);
方法 2:
I found the solution.
@override
Stream<Transition< GithubSearchEvent, GithubSearchState >> transformEvents(
Stream< GithubSearchEvent > events, transitionFn) {
return events
.debounceTime(const Duration(milliseconds: 300))
.switchMap((transitionFn));
}
方法 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);
};
}
(by Suhas Shelar、user2220771、Suhas Shelar、Thioby)
參考文件