bloc_scope 1.0.4 copy "bloc_scope: ^1.0.4" to clipboard
bloc_scope: ^1.0.4 copied to clipboard

The [bloc_scope] package helps you to easily cancel the futures and streams in case of BLOC or Cubit disposing.

AsyncBlocScope #

The AsyncBlocScope mixin provides enhanced asynchronous handling for Dart's Bloc pattern. It introduces utilities for managing asynchronous operations and subscriptions within a Bloc.

Features #

  • Auto-Cancelable Future: Ensures asynchronous functions are automatically canceled when the associated Bloc is closed. If canceled, the future throws an exception to indicate termination.
  • Auto-Cancelable Stream: Create a stream that produces subscriptions that automatically unsubscribe when the associated Bloc is closed, preventing memory leaks.
  • Silent Auto-Cancelable Future: Similar to an auto-cancelable future but ignores the result and does not propagate exceptions upon cancellation.

Usage #

To use AsyncBlocScope, simply mixin the AsyncBlocScope class in your Bloc:

class MyCubit extends Cubit<MyState> with AsyncBlocScope {
  // Your bloc implementation here
}

Auto-Cancelable/Silent Auto-Cancelable Future #

Future<void> onBound() async {
  try {
    final result = await autoCancelableFuture(() async {
      // Your asynchronous logic here
      return someValue;
    });


    // The result is available here
  } on FutureExecutionInterrupted catch (e) {
    // Handle the exception thrown on cancellation
  }
}

Future<void> onBound() async {
  final result = await silentAutoCancelableFuture(() async {
    // Your asynchronous logic here
    return someValue;
  });
}

Note: When using silentAutoCancelableFuture, if the future is canceled, it completes without returning a result, and no exception is thrown. So it's ignored.

Auto-Cancelable Subscriptions #

final streamSubscription = autoCancelableStream(
 _contactRepository.subscribeForChanges(),
).listen(_onGetsContacts);

Error Handling #

  • If an unhandled exception occurs inside an unawaited future within autoCancelableFuture or silentAutoCancelableFuture, it will be caught by onUnhandledError callback.
  • Override the onUnhandledError method to manage unhandled exceptions.
3
likes
150
points
62
downloads

Publisher

verified publisheryhdart.com

Weekly Downloads

The [bloc_scope] package helps you to easily cancel the futures and streams in case of BLOC or Cubit disposing.

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

Dependencies

async, bloc, meta

More

Packages that depend on bloc_scope