gpt4 book ai didi

收到新事件时,Flutter Bloc 取消正在运行的事件

转载 作者:行者123 更新时间:2023-12-05 01:52:01 24 4
gpt4 key购买 nike

我有以下 Bloc

class DeviceBloc extends Bloc<DeviceEvent, DeviceState> {
DataRepository repository;

DeviceBloc({@required this.repository}) : super(DeviceInitialState()) {
on<FetchDevicesEvent>(onFetchResources);
}

Future<void> onFetchResources(
FetchDevicesEvent event, Emitter<DeviceState> emit) async {
emit.call(DeviceLoadingState());

try {
List<DeviceResource> devices = await repository.getResources(event.type);
emit.call(DeviceLoadedState(devices: devices));
} catch (e) {
emit.call(DeviceErrorState(message: e.toString()));
}
}
}

当 FetchDevicesEvent 事件被触发时,它会启动一个长时间运行的任务,如果在运行的任务完成之前收到额外的 FetchDevicesEvent 事件,错误的结果将返回给调用者。如何暂停等待的任务并始终在收到新的 FetchDevicesEvent 后立即开始新任务?

最佳答案

自己通过使用 transformer: restartable() 从 bloc_concurrency 包中找到了解决方案

class DeviceBloc extends Bloc<DeviceEvent, DeviceState> {
DataRepository repository;

DeviceBloc({@required this.repository}) : super(DeviceInitialState()) {
on<FetchDevicesEvent>(
onFetchResources,
transformer: restartable(),
);
}

Future<void> onFetchResources(
FetchDevicesEvent event, Emitter<DeviceState> emit) async {
emit.call(DeviceLoadingState());

try {
final List<DeviceResource> devices =
await repository.getResources(event.type);
emit.call(DeviceLoadedState(devices: devices));
} catch (e) {
emit.call(DeviceErrorState(message: e.toString()));
}
}

关于收到新事件时,Flutter Bloc 取消正在运行的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71841125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com