要终止当前正在输出的内容,可以使用以下代码:
public class OpenAIHXTSocketEventSourceListener extends EventSourceListener {
private volatile boolean stop = false;
/**
* {@inheritDoc}
*/
@SneakyThrows
@Override
public void onEvent(EventSource eventSource, String id, String type, String data) {
if (stop) {
eventSource.close();
return;
}
// 输出内容
}
public void stop() {
stop = true;
}
}
在代码中添加了一个 boolean 类型的变量 stop,用于标记是否需要停止输出。在 onEvent 方法中,如果 stop 为 true,则调用 eventSource.close() 方法关闭连接,并直接返回,不再输出内容。在外部需要停止输出时,调用 stop 方法即可。