简体   繁体   中英

Async request using BLoC in Flutter

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));
    });
  }
}

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));
});
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM