Created
June 30, 2023 15:31
-
-
Save vlastachu/e265c1cf2bd3959df7576e34529739cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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