Bloc: How to implement polling in flutter_bloc?

Created on 15 Aug 2019  路  1Comment  路  Source: felangel/bloc

Hey Felix, is my implementation good? I am trying to implement a functionality wherein it will call the API for every N seconds and using the dart:async Timer class. Like the example below.

So far, this is what I have tried and it is working so far.

@override
  Stream<AppConnectionState> mapEventToState(ConnectionEvent event) async* {
    if (event is Initializing) {
      yield ConnectionUninitialized();
      yield* _startConnectionPolling();
    }
    ...
  }

Stream<AppConnectionState> _startConnectionPolling() async* {
    timer = Timer.periodic(Duration(seconds: 10), (timer) async {
      var apiRes = await apiProvider.retrieveDetails();
      if (apiRes.connected)
        dispatch(Connected());
      else
        dispatch(Disconnected());
    });
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

Please advice. Thanks!

question

Most helpful comment

Hi @csarigumba 馃憢
Thanks for opening an issue!

I would not recommend implementing polling this way because by using yield* within mapEventToState you are blocking the processing of all other incoming events.

Instead, I would recommend taking a similar approach to the one described in the flutter timer tutorial.

Hope that helps 馃憤

>All comments

Hi @csarigumba 馃憢
Thanks for opening an issue!

I would not recommend implementing polling this way because by using yield* within mapEventToState you are blocking the processing of all other incoming events.

Instead, I would recommend taking a similar approach to the one described in the flutter timer tutorial.

Hope that helps 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ricktotec picture ricktotec  路  3Comments

RobPFarley picture RobPFarley  路  3Comments

timtraversy picture timtraversy  路  3Comments

komapeb picture komapeb  路  3Comments

nerder picture nerder  路  3Comments