第 8 节,共 25 节

数据流

目录
Querywindowcommands.rsservice.rsstore.rsdtoCommandwindowcommands.rsHandleupdateEffectEventactorSnapshotevents.rsemitwindow

8.1. 查询(读取)

window ─invoke─► app/<s>/commands.rs ─► core/<s>/service.rs ─► core/<s>/store.rs
                        ◄── dto.rs ◄──────── model ◄──────────────────┘

读取不经过 Actor,除非它读取的就是该 Actor 的状态。那时它从句柄读取最新的 Snapshot,而不发送消息。

8.2. 命令(变更)

没有后台状态时(保存一个设置、创建一个文件):

window ─invoke─► commands ─► service ─► logic (decision) ─► store / drivers ─► result

有后台状态时(一次运行、一段对话、一次录音):

window ─invoke─► commands ─► Handle.send(Msg)
                                  │
                 actor ◄──────────┘
                   update(&mut State, Msg) -> Vec<Effect>     pure function
                   for e in effects: execute(e)               I/O: drivers, store, timers
                   snapshot.send(State.view())                the window gets a new view

8.3. 事件(后端 → 窗口)

事件只从 app/<s>/events.rs 发出。core 中的切片通过 watch::Sender<Snapshot> 或 broadcast::Sender<Event> 发布变化。events.rs 订阅它们并调用 emit。这让 core 对窗口一无所知,也让前端对每个切片的事件来源只有一个位置。事件名遵循 <slice>:<event>,例如 recording:snapshot。

app/src/recording/events.rs:

pub fn spawn(app: AppHandle, recordings: recording::Handle) {
    let mut snapshots = recordings.subscribe();
    tauri::async_runtime::spawn(async move {
        while snapshots.changed().await.is_ok() {
            let view = RecordingsDto::from(&*snapshots.borrow());
            if app.emit("recording:snapshot", view).is_err() {
                break;
            }
        }
    });
}

8.4. 高频数据流

有些切片会产生大量小事件:日志行、转写出的单词、进度刻度。不要每一行都发出一个 Tauri 事件。在 core 中给切片一个有界通道:一个属于该切片自己的小型发送端类型(例如第 20.3 节中的 WordSink),它的 send 从不等待,并返回发生了什么,例如 Sent::Delivered、Sent::Dropped 或 Sent::Closed。让 app/<s>/events.rs 拥有一个泵(pump),每隔几毫秒把这些行批量送入 tauri::ipc::Channel。有界通道就是背压:窗口处理变慢时,切片会知道(Sent::Dropped),而不是把内存填满;当不再有人监听时(Sent::Closed),切片可以停下来。批处理、通道和帧率都是入口的关注点,留在 app 中。