Re: [whatwg/streams] 'Splitter' stream? (#1030)

I don't know what you really want to do, because your code doesn't type check.

The basic of ReadableStream is that only the creator can push data into it, so instead let user of `StreamSplitter` create the stream, `StreamSplitter` should create the stream itself and give it to the user.

Like this

```ts
export class StreamSplitter implements UnderlyingSink {
    private _writable: WritableStream;

    constructor(readonly shouldSplit: (chunk: any) => boolean, readonly createReadable: (readable: ReadableStream) => void) {
    }

    private createNewReadable() {
        if (this._writable) {
            this._writable.getWriter().close();
        }

        // Create a passthrough stream pair
        // Writing to `writable` will pipe the data to `readable`
        const { readable, writable } = new TransformStream();
        this._writable = writable;

        // Pass the `readable` to the user of `StreamSplitter`
        this.createReadable(readable);
    }

    start(controller: any) {
        this.createNewReadable();
    }

    write(chunk: any, controller: any) {
        if (this.shouldSplit(chunk)) {
            this.createNewReadable();
        }
        this._writable.getWriter().write(chunk);
    }

    close() {
        this._writable.getWriter().close();
    }

    abort(error: any) {
        this._writable.getWriter().abort();
    }
}

declare const readable: ReadableStream<string>;
declare const thePattern: string;
declare function createMyRemainingTransforms(): TransformStream<string, string>;
declare function createMyWritableFileStream(counter: number): WritableStream<string>;

let counter = 0;
readable.pipeTo(new WritableStream(new StreamSplitter(
    (chunk: string) => { return chunk.includes(thePattern); },
    (readable) => {
        counter++;
        return readable
            .pipeThrough(createMyRemainingTransforms())
            .pipeTo(createMyWritableFileStream(counter));
    }
)));
```

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

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

Received on Thursday, 17 February 2022 02:27:47 UTC