Hey everyone! I'm working with a ReadableStream that I received from an Ollama LLM AI, and I'm trying to figure out how to cancel the stream while it's in use. I've noticed that when I call `message.cancel()`, it seems to be too late because the stream is already being read by a locked reader. Is there a way to stop this reader or cancel the stream altogether? Here's a snippet of my code for context:
```javascript
for await (const part of message) {
if (!props.cancelStream) {
finalMessage.value.model = part.response_metadata.model;
finalMessage.value.content += part.content;
}
}
```
I've tried adding an `if` statement to check for cancellation, but it doesn't seem to work at this point. By the way, I'm developing this in a Vue.js 3 environment. Any suggestions?
1 Answer
Have you tried using the `cancel()` method directly on the reader? You can access the reader like this:
```javascript
const reader = readable.getReader();
reader.cancel();
reader.releaseLock();
```
This should let you cancel even if the stream is locked!
Thanks for the tip! I was previously trying to cancel the stream directly. After incorporating your suggestion, my code looks like this:
```javascript
for await (const part of message) {
if (!props.cancelStream) {
finalMessage.value.model = part.response_metadata.model;
finalMessage.value.content += part.content;
} else {
const reader = message.getReader();
reader.cancel();
reader.releaseLock();
}
}
```
But now I'm getting an error stating **Cannot get a new reader for a readable stream already locked by another reader.** What am I doing wrong?