> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/operation-and-stream-types.md).

# 操作和流类型

介绍 Unity SDK 所有脚本 API 共用的异步结果和流类型，以及它们解决的问题。

大多数执行异步工作的 SDK 方法会返回 `IConvaiOperation<T>` 而不是 `Task<T>`。生成连续值序列的方法会返回 `IConvaiStream<T>`。这些类型旨在兼容 Unity 协程系统、C# async/await 和由进度驱动的流程，而无需在整个代码库中强制依赖 `Task` 。有关用法模式和代码示例，请参阅 [异步模式](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/async-patterns.md).

***

### 为什么要使用自定义异步类型？

| 要求            | `Task<T>`              | `IConvaiOperation<T>`               |
| ------------- | ---------------------- | ----------------------------------- |
| 可用于协程         | 否                      | 是 — `ToCoroutine()`                 |
| 无需异常即可获取类型化错误 | 否                      | 是 — `Error` 属性                      |
| 进度报告          | 否                      | 是 — `Progress` 属性                   |
| 直接 `await`    | 是                      | 是 — `GetAwaiter()`                  |
| 取消            | 通过 `CancellationToken` | 通过 `CancellationToken` + `Cancel()` |

***

### `IConvaiOperation<T>`

任何 SDK 异步操作的结果句柄。以下方法会返回该句柄： `ConnectAsync`, `DisconnectAsync`, `StartListeningAsync`, `WaitForCharacterReadyAsync`以及其他方法。

#### 状态属性

| 属性             | 类型                | 说明                                                          |
| -------------- | ----------------- | ----------------------------------------------------------- |
| `Status`       | `OperationStatus` | 操作当前的生命周期状态                                                 |
| `IsCompleted`  | `bool`            | 当状态为 `Succeeded`, `Faulted`或 `Canceled`                     |
| `IsSuccessful` | `bool`            | 当状态为 `Succeeded`                                            |
| `IsCanceled`   | `bool`            | 当状态为 `Canceled`                                             |
| `HasError`     | `bool`            | 当状态为 `Faulted`                                              |
| `Error`        | `ConvaiError`     | 在 `HasError` 为 true 时填充；操作成功或处于待处理状态时为默认值                   |
| `Progress`     | `float`           | 范围为 0.0–1.0 的完成度估算。并非所有操作都会报告细粒度进度——请检查 `Status` 以确认操作是否完成。 |

#### 异步/等待

| 成员             | 说明                                                                                 |
| -------------- | ---------------------------------------------------------------------------------- |
| `GetAwaiter()` | 返回一个 `TaskAwaiter<T>`。支持直接使用 `await operation` 。失败时抛出 `ConvaiOperationException` 。 |
| `AsTask()`     | 返回底层的 `Task<T>`。如果需要传递给基于 Task 的 API（例如 `Task.WhenAll`.                            |

#### 协程

| 成员                                                                            | 说明                                                                                          |
| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `ToCoroutine(Action<T> onSuccess = null, Action<ConvaiError> onError = null)` | 返回一个 `IEnumerator`。传递给 `StartCoroutine()`. `onSuccess` 接收结果； `onError` 在操作失败时接收错误。两个回调均为可选。 |

#### 链式调用

| 成员                                                   | 说明                                                               |
| ---------------------------------------------------- | ---------------------------------------------------------------- |
| `ContinueWith<TNext>(Func<T, TNext> selector)`       | 同步转换。返回一个新的 `IConvaiOperation<TNext>` ，其结果为 selector 的返回值。       |
| `ContinueWith<TNext>(Func<T, Task<TNext>> selector)` | 异步转换。返回一个新的 `IConvaiOperation<TNext>` ，当 selector 任务完成时，该操作也会完成。 |

`ContinueWith` 传播错误——如果源操作发生故障，链式操作也会以相同的错误发生故障，且不会调用选择器。

#### 取消

| 成员         | 说明                                       |
| ---------- | ---------------------------------------- |
| `Cancel()` | 请求协作式取消。当 SDK 确认请求后，操作状态将变为 `Canceled` 。 |

***

### `OperationStatus` 枚举

| 值               | 说明                 |
| --------------- | ------------------ |
| `Created` (0)   | 操作已创建，但尚未启动        |
| `Running` (1)   | 操作正在执行             |
| `Succeeded` (2) | 操作已成功完成。结果可用。      |
| `Faulted` (3)   | 操作失败。 `Error` 已填充。 |
| `Canceled` (4)  | 操作在完成前已取消          |

**生命周期：** `Created → Running → Succeeded / Faulted / Canceled`

***

### `ConvaiError` 结构体

携带结构化错误信息，无需进行异常处理。当 `IConvaiOperation<T>.Error` 且 `HasError` 为 true 时填充。

| 成员          | 类型          | 说明                                  |
| ----------- | ----------- | ----------------------------------- |
| `Code`      | `string`    | 机器可读的错误代码，例如 `"connection.timeout"` |
| `Message`   | `string`    | 人类可读的描述                             |
| `Exception` | `Exception` | 底层异常（如果错误源自某个异常）。可能为 `null`.        |
| `IsEmpty`   | `bool`      | 当这是默认（无错误）值时为 True                  |

#### 静态工厂方法

```csharp
ConvaiError.FromException(Exception exception, string code = "exception")
```

从异常创建一个 `ConvaiError` 。在自定义错误处理路径中，可使用此方法根据捕获的异常构造错误。

`ConvaiError` 是一个结构体，并支持 `Equals`, `GetHashCode`和 `ToString()`.

***

### `ConvaiOperationException`

当你对某个 `await` 进行等待时抛出 `IConvaiOperation<T>` 发生故障的操作。继承自 `Exception`.

| 属性        | 类型       | 说明                                             |
| --------- | -------- | ---------------------------------------------- |
| `Code`    | `string` | 底层 `ConvaiError` 中的错误代码 — 与 `ConvaiError.Code` |
| `Message` | `string` | 继承自 — 人类可读的描述                                  |

**`HasError` 与抛出的异常：**

* **协程** (`ToCoroutine`）：错误会传递给 `onError` 回调。不会抛出异常。
* **异步/等待**：操作发生故障时会抛出 `ConvaiOperationException`。使用 `try/catch`.
* `HasError` 在 `true` 两种情况下都是如此 — 无论采用哪种使用模式，您都可以随时轮询它。

{% hint style="warning" %}
使用异步/等待时， **取消会抛出 `OperationCanceledException`**，而不是 `ConvaiOperationException`。始终捕获这两种异常：

```csharp
try
{
    await manager.ConnectAsync(destroyCancellationToken);
}
catch (ConvaiOperationException ex) { /* SDK error */ }
catch (OperationCanceledException)  { /* canceled   */ }
```

{% endhint %}

***

### `IConvaiStream<T>`

由会随时间生成连续值序列的方法返回，例如流式传输转录文本令牌或音频帧。实现了 `IAsyncDisposable`.

#### 属性

| 属性       | 类型             | 说明                     |
| -------- | -------------- | ---------------------- |
| `Status` | `StreamStatus` | 流的当前生命周期状态             |
| `Error`  | `ConvaiError`  | 当 `Status` 为 `Faulted` |

#### 方法

| 方法                                             | 返回                    | 说明                           |
| ---------------------------------------------- | --------------------- | ---------------------------- |
| `ReadAllAsync(CancellationToken ct = default)` | `IAsyncEnumerable<T>` | 在项目到达时逐个生成。流结束时完成。支持取消。      |
| `DisposeAsync()`                               | `ValueTask`           | 释放流并清理资源。始终通过 `await using`. |

```csharp
await using var stream = GetSomeStream();
await foreach (var item in stream.ReadAllAsync(destroyCancellationToken))
{
    ProcessItem(item);
}
```

***

### `StreamStatus` 枚举

| 值               | 说明                  |
| --------------- | ------------------- |
| `Created` (0)   | 流已创建，但尚未开始传输        |
| `Streaming` (1) | 流正在持续输出项目           |
| `Completed` (2) | 所有项目均已交付；流已正常结束     |
| `Faulted` (3)   | 流遇到错误。 `Error` 已填充。 |
| `Canceled` (4)  | 流在完成前已取消            |

**生命周期：** `Created → Streaming → Completed / Faulted / Canceled`

***

### `Unit` 结构体

```csharp
Unit.Value // 唯一实例
```

当操作没有有意义的返回值时，用作类型参数的 void 等效类型。诸如 `DisconnectAsync()` 和 `StopListeningAsync()` 会返回 `IConvaiOperation<Unit>` — `await` 它们是为了执行副作用，而不是获取结果。

`Unit` 支持相等性比较（`==`, `!=`, `Equals`）和 `ToString()` 返回 `"()"`.

***

### 后续步骤

有关使用这些类型的实际消费模式，请参阅 [异步模式](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/async-patterns.md)。有关所有返回 `IConvaiOperation<T>`的方法，请参阅 [ConvaiManager API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/convaimanager-api.md) 和 [Character & Player API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/character-and-player-api.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/operation-and-stream-types.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
