PackRuble / cardoteka

The best type-safe wrapper over SharedPreferences. ⭐ Why so? -> strongly typed cards for access to storage -> don't think about type, use get|set -> can work with nullable values -> callback based updates
https://t.me/+AkGV73kZi_Q1YTMy
Apache License 2.0
3 stars 0 forks source link

Way to remove a callback using `Watcher.attach` + `ChangeNotifier` #9

Open PackRuble opened 9 months ago

PackRuble commented 9 months ago

I propose to discuss what the functionality should look like to allow convenient use of Cardoteka with the Watcher mixin to attach a callback to a ChangeNotifier object.

I'm considering this kind of hagfish for now:

mixin NotifierDetacher on ChangeNotifier {
  List<VoidCallback>? _onDisposeCallbacks;

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

  @override
  void dispose() {
    _onDisposeCallbacks?.forEach((cb) => cb.call());
    _onDisposeCallbacks = null;

    super.dispose();
  }
}

This will allow you to do this in the future:

class OrderNotifier with ChangeNotifier, NotifierDetacher {
  final _orders = <String>[];

  void addOrder(String value) {
    _orders.add(value);
    notifyListeners();
    print('New order: $value');
  }
}

And then attach the wiretap like this:

void main() {
  // ignore_for_file: definitely_unassigned_late_local_variable
  // to do: initialize
  late CardotekaImpl cardoteka;
  late Card<String> lastOrderCard;

  final notifier = OrderNotifier();
  cardoteka.attach(
     lastOrderCard,
     notifier.addOrder, // <- nice bonus :)
     detacher: notifier.onDispose, // <- THIS
  );

  cardoteka.set(lastOrderCard, '#341');
  // 1. a value was saved to storage
  // 2. console-> New order: #341
}

Please, semantics, logic, and naming are both important. Share your thoughts :) 🙏