[whatwg/streams] Unified way to clean up after ReadableStream finished/errored/was canceled (Issue #1329)

### What is the issue with the Streams Standard?

It seems like the standard doesn't provide a simple way to guarantee resources are cleaned up after a ReadableStream is closed for any reason.  I mean, I could make a shared `cleanup` function, but I have to call it from three different places:

```ts
function cleanup() {
  // free resources
}

return new ReadableStream({
  async start(controller) {
    try {
      ...
    } catch (error) {
      cleanup()
    }
  },
  async pull(controller) {
    try {
      ...
    } catch (error) {
      cleanup()
    }
  },
  async cancel(controller) {
    cleanup()
  }
})
```

I think it should also accept a `closed` method on `underlyingSource` that will be called after the stream has closed for any reason:

```ts
return new ReadableStream({
  async start(controller) {
    ...
  },
  async pull(controller) {
    ...
  },
  async closed() {
    // cleanup code
  },
})
```

We can do something like this in userland, but if we leave it up to userland, there's a lot more risk that developers will miss one of the three cases where they need to cleanup.  If the API provides a `closed` method itself, then there will be less resource leaks in the wild.



-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/streams/issues/1329
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/streams/issues/1329@github.com>

Received on Monday, 28 October 2024 15:44:40 UTC