Async request using BLoC in Flutter

梦想的初衷 提交于 2021-01-28 06:24:13

问题


I would like download the data, but also use the application all the time.

Can you tell me if it's right solution?

The case is we press button download and call funtion bloc.dispatch(Event.download());

In mapEventToState in _Download event we reqest data. But we don't wait for response because we don't want to block others events which are changing view.

So I create Future and after getting response I call event _UpdateData() where I process downloaded data and generate state with them.

It's ok? There is _requestTime parameter to check if it's last request.

class Bloc {
  DateTime _requestTime;

  @override
  Stream<State> mapEventToState(Event event) async* {
    if (event is _Download) {
      yield DownloadingState();
      _request();
    } else if (event is _UpdateData) {
      if(!event.requestTime.isBefore(_requestTime))
        yield DownladedState(event.response);
    }
  }

  _request() {
    _requestTime = DateTime.now();
    repository.downloadData().then((response) {
      dispatch(_UpdateData(response));
    });
  }
}

回答1:


Let me know if it works

Changeadded yield* in front of _request

@override
Stream<State> mapEventToState(Event event) async* {
if (event is _Download) {
  yield DownloadingState();
 yield* _request();
} else if (event is _UpdateData) {
  if(!event.requestTime.isBefore(_requestTime))
    yield DownladedState(event.response);
}
}

_request() async*{
_requestTime = DateTime.now();
repository.downloadData().then((response) {
  dispatch(_UpdateData(response));
});
}
}


来源:https://stackoverflow.com/questions/59770983/async-request-using-bloc-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!