listen method

ListenableSubscription listen(
  1. void handler(
    1. T,
    2. ListenableSubscription
    )
)

let you work with a ValueListenable as it should be by installing a handler function that is called on any value change of this and gets the new value passed as an argument. It returns a subscription object that lets you stop the handler from being called by calling cancel() on the subscription. The handler get the subscription object passed on every call so that it is possible to uninstall the handler from the handler itself.

example:


final listenable = ValueNotifier<int>(0);
final subscription = listenable.listen((x, _) => print(x));

final subscription = listenable.listen((x, subscription) {
  print(x);
  if (x == 42){
     subscription.cancel();
  }
}

Implementation

ListenableSubscription listen(
  void Function(T, ListenableSubscription) handler,
) {
  final subscription = ListenableSubscription(this);
  subscription.handler = () => handler(this.value, subscription);
  this.addListener(subscription.handler);
  return subscription;
}