Module 04: ClaudeAsyncClient
Reactive, composable, non-blocking chains with Project Reactor.What You’ll Learn
- Creating clients with
ClaudeClient.async() - The TurnSpec pattern for response handling
- Multi-turn conversations with flatMap chaining
- When to choose async vs sync clients
ClaudeSyncClient vs ClaudeAsyncClient
Both clients provide identical capabilities. They differ only in programming paradigm:| Feature | ClaudeSyncClient | ClaudeAsyncClient |
|---|---|---|
| Style | Blocking, sequential | Reactive, composable |
| Returns | String, Iterable<Message> | TurnSpec → Mono/Flux |
| Multi-turn | Supported | Supported |
| Hooks/MCP | Supported | Supported |
| Best for | Simple scripts, CLI tools | Reactive apps, composition |
TurnSpec: Response Handling
ClaudeAsyncClient returns a TurnSpec that provides three ways to handle responses:
| Method | Returns | Use Case |
|---|---|---|
.text() | Mono<String> | Collected text, enables flatMap chaining |
.textStream() | Flux<String> | Streaming text as it arrives |
.messages() | Flux<Message> | All message types for metadata access |
Multi-Turn Conversation
The.text() method returns Mono<String>, enabling elegant flatMap chaining:
Text Streaming
For streaming text as it arrives:Full Message Access
When you need metadata, tool use details, or cost information:Key Points
- Factory pattern: Use
ClaudeClient.async()to create clients - TurnSpec pattern:
connect()/query()returnTurnSpec, not void - flatMap for multi-turn: Chain turns with
.text().flatMap(r -> ...) - Non-blocking: Use
.subscribe(), avoid.block() - Same capabilities: Hooks, MCP, permissions all work identically to sync
ClaudeAsyncClient Methods
| Method | Returns | Description |
|---|---|---|
connect(prompt) | TurnSpec | Start session with prompt |
query(prompt) | TurnSpec | Send follow-up message |
onMessage(handler) | ClaudeAsyncClient | Register cross-turn message handler |
onResult(handler) | ClaudeAsyncClient | Register cross-turn result handler |
close() | Mono<Void> | End session |
TurnSpec Methods
| Method | Returns | Description |
|---|---|---|
.text() | Mono<String> | Collected text response |
.textStream() | Flux<String> | Streaming text |
.messages() | Flux<Message> | All message types |
Builder Options
When to Choose
| Scenario | Recommendation |
|---|---|
| Simple script or CLI | ClaudeSyncClient |
| Traditional blocking app | ClaudeSyncClient |
| Simpler debugging | ClaudeSyncClient |
| Reactive application | ClaudeAsyncClient |
| Composing with other reactive streams | ClaudeAsyncClient |
| High-concurrency server | ClaudeAsyncClient |