81 Resource ownership
A subscription created inside a ResourceOwner context registers with that owner. Explicit close() releases it early and removes it from the owner's resource list; a host such as a GUI component can later clean up resources it still owns.
withContext provides the owner while its callback runs. The returned subscription retains that ownership relation, so closing it after the callback exits still removes the registration. This example verifies registration and early release, not host destruction.
norm
import std.io.Resource
import std.io.ResourceOwner
import std.context.withContext
import std.observation.onChange
class Owner implements ResourceOwner {
List<Resource> resources = []
Void own(Resource resource) { resources.add(resource) }
Void release(Resource resource) { resources = [for (item : resources) if (item != resource) item] }
Void execute(Function<Void()> action) { withContext<ResourceOwner>(value: this, action: action) }
}
class Task { String title = "Draft" }
main() {
Owner owner = Owner()
Task task = Task()
Resource subscription = withContext<ResourceOwner, Resource>(value: owner, action: () { task.title.onChange {} })
printLine(owner.resources.size())
subscription.close()
printLine(owner.resources.size())
}Expected output:
text
1
0Try it: Create a second subscription without closing it and inspect the owner's list.
Precise rules: Reference.