listen method

ListenableSubscription listen(
  1. void callback()
)

Listen to the Listenable.

The standard way to subscribe using addListener requires using a method as a callback, which is then used in removeListener:

void _listener() {...}

listenable.addListener(_listener);
...
listenable.removeListener(_listener);

If you use a closure, you need to store a reference to it somewhere so that you can later pass it to removeListener:

final closure = () {...};
listenable.addListener(closure);
...
listenable.removeListener(closure);

This method adds the same interface used in Stream api:

ListenableSubscription subscription = listenable.listen(() {...});
...
subscription.cancel();

It stores a reference to the listener inside ListenableSubscription so that it can later remove listener using ListenableSubscription.cancel.

Implementation

ListenableSubscription listen(void Function() callback) {
  addListener(callback);
  return ListenableSubscription._(this, callback);
}