closeable.dart 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import 'dart:async';
  2. import 'package:meta/meta.dart';
  3. import 'package:get/get.dart';
  4. class Closeable{
  5. @protected
  6. Future<void> onClose()async{}
  7. @protected
  8. void listenStream<T>(Stream<T> stream, void Function(T event) onData){
  9. _subscriptions.add(stream.listen(onData));
  10. }
  11. @protected
  12. void listenRx<T>(Rx<T> rx, void Function(T event) onData){
  13. _subscriptions.add(rx.listen(onData));
  14. }
  15. @protected
  16. void addTimer(Duration interval, void Function() callback){
  17. _timers.add(Timer.periodic(interval, (timer) {
  18. callback();
  19. }));
  20. }
  21. @protected
  22. void rxBindRx<T>({required Rx<T> dst, required Rx<T> src}){
  23. dst.bindStream(src.stream);
  24. _rxList.add(dst);
  25. }
  26. void close(){
  27. _isActive=false;
  28. for(final one in _subscriptions){
  29. one.cancel();
  30. }
  31. for(final one in _timers){
  32. one.cancel();
  33. }
  34. for(final one in _rxList){
  35. one.close();
  36. }
  37. onClose().then((value) => _closeController.close());
  38. }
  39. Future<void> join(){
  40. _joinFuture??=()async{
  41. try{
  42. await for (final _ in _closeController.stream) {}
  43. }finally{}
  44. }();
  45. return _joinFuture!;
  46. }
  47. final _closeController = StreamController();
  48. Future<void>? _joinFuture;
  49. var _isActive=true;
  50. bool get isActive=>_isActive;
  51. final List<Timer> _timers = [];
  52. final _subscriptions = <StreamSubscription>[];
  53. final _rxList = <Rx>[];
  54. }