【问题标题】:Flutter BLoC event race conditionFlutter BLoC 事件竞争条件
【发布时间】:2021-12-07 02:34:43
【问题描述】:

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

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

预期结果是我们在此处丢弃来自请求日期=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));
    }
  }
}

【问题讨论】:

    标签: flutter dart bloc flutter-bloc


    【解决方案1】:

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

    您可以在此处阅读有关转换器的更多信息: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));
        }
      }
    }
    

    【讨论】:

    • 这个版本之前的事件是顺序处理的吗?
    • 如果你的意思是 mapEventToState 那么是的。这里有一个关于如何让 mapEventToState 并行运行的问题:stackoverflow.com/questions/66700401/… 简而言之,你不能在 mapEventToState 中等待,而是调用另一个异步方法。
    猜你喜欢
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2018-10-08
    • 1970-01-01
    相关资源
    最近更新 更多