attachStream method
Transfers close notification to one stream without strongly rooting it.
cancel must be an unbound function: the notice keeps only a weak target,
but retains this operation so an abandoned target cannot strand leases.
Implementation
void attachStream(Object target, Future<void> Function(Object) cancel) {
if (_released || _stream != null) {
throw StateError('Resource operation cannot attach another stream.');
}
final notice = _ResourceStreamNotice(this, target, cancel);
_stream = notice;
(_group.streams ??= []).add(notice);
for (final control in _group.leases.keys.toList(growable: false)) {
notice.attach(control);
if (_released) return;
}
// All links exist before cancellation can synchronously reenter cleanup.
for (final control in notice.controls.toList(growable: false)) {
if (_released) break;
if (control.state != ResourceState.open) control._cancelStreams([notice]);
}
}