Flutter BLoC 事件竞争条件

RMK*_*RMK 4 dart flutter bloc flutter-bloc

假设我们有一个应用程序,其中用户有一个日历,他可以在其中选择他想要获取事件列表的日期。当用户选择日期时,我们添加一个事件CalendarSelectedDateChanged(DateTime)。每次我们收到此类事件时,Bloc 组件都会从 API 获取数据。我们可以想象一下以不同的延迟收到响应的情况。这将产生以下场景:

  • 用户点击日期 1
  • API 调用使用参数 date=1 进行
  • 状态设置为加载中
  • 用户点击日期 2
  • 状态设置为加载中
  • 收到请求 date=2 的响应
  • 状态设置为 dataLoadSuccess(date=2)

预期结果是我们在这里丢弃请求 date=1 的响应

  • 收到请求日期=1 的响应
  • 状态设置为 dataLoadSuccess(date=1)

我们如何以最优雅的方式解决这种竞争条件(最好同时解决应用程序中的所有 BLoC)?

这是会产生此类问题的示例代码:

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {

  ExampleBloc()
      : super(ExampleDataLoadInProgress(DateTime.now())) {
    on<ExampleSelectedDateChanged>((event, emit) async {
      await _fetchData(event.date, emit);
    });
  }

  Future<void> _fetchData(DateTime selectedDate,
      Emitter<ExampleState> emit,) async {
    emit(ExampleDataLoadInProgress(selectedDateTime));
    try {
      final data = callAPI(selectedDateTime);
      emit(ExampleDataLoadSuccess(data, selectedDate));
    } on ApiException catch (e) {
      emit(ExampleDataLoadFailure(e, selectedDateTime));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

RMK*_*RMK 6

默认情况下,所有事件都是同时处理的,您可以通过设置自定义转换器来更改该行为:

您可以在这里阅读有关变压器的更多信息:https://pub.dev/packages/bloc_concurrency

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {

  ExampleBloc()
      : super(ExampleDataLoadInProgress(DateTime.now())) {
    on<ExampleSelectedDateChanged>((event, emit) async {
      await _fetchData(event.date, emit);
    },
      transformer: restartable(), // ADD THIS LINE 
    );
  }

  Future<void> _fetchData(DateTime selectedDate,
      Emitter<ExampleState> emit,) async {
    emit(ExampleDataLoadInProgress(selectedDateTime));
    try {
      final data = callAPI(selectedDateTime);
      emit(ExampleDataLoadSuccess(data, selectedDate));
    } on ApiException catch (e) {
      emit(ExampleDataLoadFailure(e, selectedDateTime));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你的意思是mapEventToState那么是的。这是一个关于如何使mapEventToState并行运行的问题:/sf/ask/4669028101/ 简而言之,你不能在mapEventToState中等待,而是调用另一个异步方法。 (2认同)