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;
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.