Bloc: Scheduling a non blocking future BlocEvent

Created on 14 May 2020  路  4Comments  路  Source: felangel/bloc

Is your feature request related to a problem? Please describe.
I created a Bloc that interacts with the Pi-hole API. The API can be used to send a 'sleep' command, which disables a Pi-hole for some duration. The 'sleep' command is sent by my Bloc using a a BlocEvent.

Once the duration has elapsed, I want the Bloc to send an event to itself in order to update its state. I naively tried using a simple Future.await, but this prevents other external events from landing during the duration. See this example (which is commented out): https://github.com/sterrenburg/flutterhole/blob/2ae85a199c265060b66c86e27bfc5a9648cba67f/lib/features/pihole_api/blocs/pi_connection_bloc.dart#L113-L118.

Describe the solution you'd like
Is there a way to schedule a Bloc.add(BlocEvent) without blocking the event stream? I am not sure if this is a problem related to this package, or rather with Dart/Flutter, so please let me know if this is the wrong place.

Describe alternatives you've considered
I have looked into the scheduler library to no avail, and currently I am simply sending events from a build method like this (yuck): https://github.com/sterrenburg/flutterhole/blob/2ae85a199c265060b66c86e27bfc5a9648cba67f/lib/features/pihole_api/presentation/widgets/pi_connection_status_icon.dart#L113-L116
Additional context
This issue is regarding the V5 branch of my repo at https://github.com/sterrenburg/flutterhole/tree/v5.

question

Most helpful comment

Thank you for your responses! I managed to get the expected output using Future.whenComplete without the await.

The Bloc now simply adds another event like your example:

Future.delayed(duration).whenComplete(() {
  add(PiConnectionEvent.ping());
});

All 4 comments

you could override transformEvents and apply transformer which doesn't schedule events in queue

something like this

Hi @sterrenburg 馃憢
Thanks for opening an issue!

Instead of awaiting the Future you can just use .whenComplete or unawaited to schedule adding another event to the bloc which shouldn't block the event stream.

Future.delayed(const Duration(milliseconds: 500)).whenComplete(() => add(MyEvent()));
unawaited(Future.delayed(
  const Duration(milliseconds: 500),
  () => add(MyEvent()),
));

Hope that helps 馃憤

Thank you for your responses! I managed to get the expected output using Future.whenComplete without the await.

The Bloc now simply adds another event like your example:

Future.delayed(duration).whenComplete(() {
  add(PiConnectionEvent.ping());
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

wheel1992 picture wheel1992  路  3Comments

hivesey picture hivesey  路  3Comments

clicksocial picture clicksocial  路  3Comments

tigranhov picture tigranhov  路  3Comments

abinvp picture abinvp  路  3Comments