Skip to content

Instantly share code, notes, and snippets.

@vlastachu
Created June 30, 2023 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlastachu/e265c1cf2bd3959df7576e34529739cf to your computer and use it in GitHub Desktop.
Save vlastachu/e265c1cf2bd3959df7576e34529739cf to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:flutter/widgets.dart';
// interface to close something
abstract class AppClosable {
void close();
}
// List of things that can be closed
class ClosableSubscription implements AppClosable {
final StreamSubscription subscription;
ClosableSubscription(this.subscription);
@override
void close() {
subscription.cancel();
}
}
class ClosableChangeNotifier implements AppClosable {
final ChangeNotifier notifier;
ClosableChangeNotifier(this.notifier);
@override
void close() {
notifier.dispose();
}
}
// abstract thing which contain closable things and close them when closes itself
abstract class Closer {
void addClosable(AppClosable closable);
}
extension SubscriptionClose on StreamSubscription {
void closeWith(Closer closer) {
closer.addClosable(ClosableSubscription(this));
}
}
extension ChangeNotifierClose on ChangeNotifier {
void closeWith(Closer closer) {
closer.addClosable(ClosableChangeNotifier(this));
}
}
mixin AutoCloseBloc<T> on BlocBase<T> implements Closer {
final List<AppClosable> closables = [];
@override
void addClosable(AppClosable closable) {
closables.add(closable);
}
@override
Future<void> close() {
for (final closable in closables) {
closable.close();
}
return super.close();
}
}
mixin AutoCloseWidgetState<T extends StatefulWidget> on State<T> implements Closer {
final List<AppClosable> closables = [];
@override
void addClosable(AppClosable closable) {
closables.add(closable);
}
@override
void dispose() {
for (final closable in closables) {
closable.close();
}
super.dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment