rodydavis / signals.dart

Reactive programming made simple for Dart and Flutter
http://dartsignals.dev
Apache License 2.0
438 stars 50 forks source link

Add ability to unregister a dispose callback #187

Closed jinyus closed 7 months ago

jinyus commented 7 months ago

It's generally a good practice to provide a way to unregister listeners. This is useful when you want to allow resources captured by the callback to be freed by the GC.

final completer = Completer<T>();
final unsub = subscribe(completer.complete);

// if the signal is disposed before a new value is emitted,
// complete the future with the current value.
// Without this, the future would hang indefinitely
final rmCallback = onDispose(() {
   if (completer.isCompleted) return;
   completer.complete(peek());
});

final result = await completer.future;

unsub();

// the Completer was captured by the dispose closure
// this allows the completer to be garbage collected
rmCallback(); 

return result;