Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Way to remove a callback using Watcher.attach + Cubit #10

Open
PackRuble opened this issue Dec 18, 2023 · 1 comment
Open

Way to remove a callback using Watcher.attach + Cubit #10

PackRuble opened this issue Dec 18, 2023 · 1 comment
Labels
discussion There's a lot to discuss enhancement New feature or request

Comments

@PackRuble
Copy link
Owner

PackRuble commented Dec 18, 2023

This is generally the same story as in issue #9 with ChangeNotifier. However, a slightly more general syntax covering both cases at once appeared in my head:

mixin Detachability {
  List<VoidCallback>? _onDisposeCallbacks;

  void onDetach(void Function() cb) {
    _onDisposeCallbacks ??= [];
    _onDisposeCallbacks!.add(cb);
  }

  @protected
  void detach() {
    _onDisposeCallbacks?.forEach((cb) => cb.call());
    _onDisposeCallbacks = null;
  }
}

Which will make it possible to do things like this:

import 'package:bloc/bloc.dart';

class CubitImpl extends Cubit<int> with Detachability {
  CubitImpl() : super(0);
  
  void setValue(int value) => emit(value);

  @override
  Future<void> close() async {
    super.detach();
    return super.close();
  }
}

Future<void> main() async {
  // initialize...
  late CardotekaImpl cardoteka;
  late Card<int> counterCard;

  final cubit = CubitImpl();
  cardoteka.attach(
    counterCard,
    cubit.setValue,
    detacher: cubit.onDetach,
  );
}

We can't seem to do anything technically with those "parent" classes that we need to extends from. This also applies to Cubit and ValueNotifier and the like. And I don't like the fact that it's very easy to forget to override the close method when adding the “Detachability” mixin.

@PackRuble
Copy link
Owner Author

Yes, the important thing here is that I wouldn't want to force users to use a conditional CubitDetachability that is a standalone implementation of abstract MyCubit extends Cubit with Detachability because that's too tight an integration with other libraries, similar to how riverpod forces the use of ConsumerWidget instead of StatelessWidget (even though there is a Consumer in the package).

@PackRuble PackRuble added enhancement New feature or request discussion There's a lot to discuss labels Dec 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
discussion There's a lot to discuss enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant