Skip to content

Commit 7ed403c

Browse files
committed
refactor: optimize event listener registration in WeatherAssistant for improved performance
1 parent 8dc9ae0 commit 7ed403c

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

src/site/markdown/getting-started.md

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,7 @@ import com.github.copilot.sdk.events.*;
235235
import com.github.copilot.sdk.json.*;
236236
import java.util.*;
237237
import java.util.concurrent.*;
238+
import java.util.concurrent.atomic.*;
238239

239240
public class WeatherAssistant {
240241
public static void main(String[] args) throws Exception {
@@ -280,6 +281,19 @@ public class WeatherAssistant {
280281
System.out.println("🌤️ Weather Assistant (type 'exit' to quit)");
281282
System.out.println(" Try: 'What's the weather in Paris?'\n");
282283

284+
var done = new AtomicReference<CompletableFuture<Void>>();
285+
286+
// Register listener once, outside the loop
287+
session.on(event -> {
288+
if (event instanceof AssistantMessageDeltaEvent delta) {
289+
System.out.print(delta.getData().getDeltaContent());
290+
} else if (event instanceof SessionIdleEvent) {
291+
System.out.println();
292+
var f = done.get();
293+
if (f != null) f.complete(null);
294+
}
295+
});
296+
283297
while (true) {
284298
System.out.print("You: ");
285299
String input = scanner.nextLine();
@@ -288,20 +302,11 @@ public class WeatherAssistant {
288302
break;
289303
}
290304

291-
var done = new CompletableFuture<Void>();
292-
293-
session.on(event -> {
294-
if (event instanceof AssistantMessageDeltaEvent delta) {
295-
System.out.print(delta.getData().getDeltaContent());
296-
} else if (event instanceof SessionIdleEvent) {
297-
System.out.println("\n");
298-
done.complete(null);
299-
}
300-
});
305+
done.set(new CompletableFuture<>());
301306

302307
System.out.print("Assistant: ");
303308
session.send(new MessageOptions().setPrompt(input)).get();
304-
done.get();
309+
done.get().get();
305310
}
306311
}
307312
}

0 commit comments

Comments
 (0)