Skip to main content

ActorHandle

Struct ActorHandle 

Source
pub struct ActorHandle<A: ActorCore> { /* private fields */ }
Expand description

actor 的控制端。

由 ActorCore::channel 创建,通常由外部控制方持有。用于发送命令、读取状态/进度、 订阅事件,以及注册异步监听。

§线程安全

ActorHandle<A> 的 Send/Sync 只取决于四个关联类型,与 actor 本身是否 Send 无关: 即使 A 是 !Send(比如握着 Rc<...> 资源的线程 actor),它照样可以放进 GUI props、 跨线程传递、塞进 Arc。

§发送命令

send_cmd 是同步的:不阻塞、不返回 future,唯一的失败原因是 actor 已停止(或所有后台端已退出)。因此可以在 GUI 回调、Drop、同步宿主里直接调用。

§读状态 / 进度

两种读法,按需选:

  • get_state / get_progress: 同步取一份最新快照,适合偶尔读一次;
  • state_rx / progress_rx: 拿 watch::Receiver 自己驱动(每帧 has_changed(),或 changed().await),适合接 GUI 帧循环。

两者都不需要 runtime;需要回调式的(op(value).await)才用 *_listen_async, 那个内部 tokio::spawn,要求调用线程有 tokio runtime。

§示例

let (context, handle) = MyActor::channel( (), ());

handle.send_cmd(()).unwrap();
let state = handle.get_state();

let listener = handle.state_listen_async(|s| async move { });
listener.cancel();

Implementations§

Source§

impl<A: AsyncActor> ActorHandle<A>

Source

pub fn state_listen_async<F, Fut>(&self, op: F) -> CancelToken
where F: FnMut(A::State) -> Fut + Send + 'static, Fut: Future<Output = ()> + Send,

异步监听状态变化。

每次状态变化时会调用 op,传入最新状态;返回的 CancelToken 调用 CancelToken::cancel 后停止监听。

§注意

内部使用 tokio::spawn,调用线程必须有 tokio runtime,否则会 panic (there is no reactor running)。同步宿主(GUI 回调、GTK/iOS 主线程等)请改用 state_rx 拿 watch::Receiver 自己拉(每帧 has_changed()),或 get_state 轮询, 或基于 get_events_rx 每帧 try_recv()。

Source

pub fn progress_listen_async<F, Fut>(&self, op: F) -> CancelToken
where F: FnMut(A::Progress) -> Fut + Send + 'static, Fut: Future<Output = ()> + Send,

异步监听进度变化。

每次进度变化时调用 op。进度是 watch 语义,中间值可能被跳过, 只保证拿到的是当时的最新值;返回的 CancelToken 调用 cancel() 后停止监听。

§注意

与 ActorHandle::state_listen_async 相同:内部 tokio::spawn,需要 tokio runtime。 同步宿主请改用 progress_rx(watch::Receiver,自己每帧拉) 或 get_progress(取当前快照)。

Source

pub fn events_listen_async<F, Fut>(&self, op: F) -> CancelToken
where F: FnMut(A::Event) -> Fut + Send + 'static, Fut: Future<Output = ()> + Send,

异步监听事件流。

每收到一个事件调用一次 op。落后超过事件通道容量时会收到 Lagged, 内部只记一条 warn 然后继续(丢事件,不重放);返回的 CancelToken 调用 cancel() 后停止监听。

§注意

与 ActorHandle::state_listen_async 相同:内部 tokio::spawn,需要 tokio runtime。

Source§

impl<A: ActorCore> ActorHandle<A>

Source

pub fn send_cmd(&self, cmd: A::Cmd) -> Result<(), SendCmdError>

向 actor 发送一条命令。

同步、不阻塞(命令通道是无界的),不会阻塞调用线程。失败只会在 actor 已停止 (ActorHandle::stop 之后,或后台端已退出)时发生。

Source

pub fn get_state(&self) -> A::State

获取 actor 的最新状态(同步快照)。

每次调用都拷贝一份 watch 的当前值,不阻塞、不需要 runtime。 适合“偶尔读一次“;想“变了就叫我“而不是轮询,用 state_rx 拿接收端自己驱动。

Source

pub fn get_progress(&self) -> A::Progress

获取 actor 的最新进度(同步快照)。

进度通道是 watch:读者只会看到最新值,中间值可能被跳过。 适合进度条、实时指标,不要拿它当消息队列用。 想订阅变化而非每次拉快照,用 progress_rx。

Source

pub fn get_events_rx(&self) -> Receiver<A::Event>

订阅事件流,返回一个 broadcast 接收端。

这是同步用法:在 GUI 帧循环里 try_recv() 即可,不需要 async runtime。 落后太多时 recv() 会返回 Lagged,需要自行决定是跳过还是重试。

Source

pub fn stop(&self)

请求 actor 停止。

只是发出取消信号(CancelToken::cancel),不会强行中断 run: 实现者需要在自己的循环里检查取消信号(如 select! 到 cancel.cancelled(), 或每轮 is_cancelled()),否则 actor 会继续跑到 run 返回为止。

Source

pub fn is_alive(&self) -> bool

actor 是否还活着。

§false 的准确含义(0.1.1 起)

actor 已结束,并且它持有的资源已经析构完。

线程壳下,run(self, ctx) 返回后 actor 自身还要 drop —— Vulkan 设备、解码器、 字体库这类“释放起来要几十毫秒“的东西。本标志在那之后才变 false, 因此用它判断“可以安全退出进程 / 可以安全复用这块资源“是成立的。

0.1.0 里它只表示“run 已返回“,比资源释放早一个窗口:依赖它做退出判断的调用方 会与后台线程的 free() 赛跑,偶发 glibc 堆损坏(corrupted double-linked list / corrupted size vs. prev_size)→ SIGABRT。详见 CHANGELOG 的 0.1.1。

反方向不成立:true 不代表 actor 干得动活 —— 阻塞调用卡死时它仍然是 true。

Source

pub fn alive_rx(&self) -> Receiver<bool>

订阅“存活状态“,actor 结束时变成 false。

false 的含义与 is_alive 相同:资源已释放完, 不只是 run 返回。

用来替代轮询 is_alive:GUI 每帧 has_changed() 一次即可(watch 语义,中间变化可丢,只关心最终值)。

后台端 drop 后 sender 也随之消失,因此 changed() 可能返回 Err —— 那同样意味着 actor 已经结束,按 false 处理即可。

Source

pub fn state_rx(&self) -> Receiver<A::State>

订阅状态变化,返回一个 watch::Receiver。

与 get_state 是一对:那个每次拉一份最新快照, 这个给你一个能“等下一次变化“的接收端。用途是自己驱动的更新循环:

  • 同步宿主(GUI 帧循环、GTK/iOS 主线程等):每帧 has_changed() 一次;
  • 异步:在 select! 里 rx.changed().await。本方法只是 watch 通道的接收端, 不需要 tokio runtime,也不会自己 spawn 任务。
let mut states = handle.state_rx();

// 每帧调一次:有变化就取新值重绘(没有就什么也不做)
if states.has_changed().unwrap_or(false) {
    let state: u32 = states.borrow_and_update().clone();
    // draw(state);
}
§语义(watch)

只保留最新值,中间值可能被跳过:actor 连续更新多次而读者没跟上,只看到最后那次。 要一条不漏地收消息,请用 get_events_rx(broadcast), 别把状态当事件流用。

§第一次 changed() 可能立刻返回

每次调用都 clone 出一个独立的接收端(各自维护“已读“位置,多个读者互不影响), 而 clone 带过来的是 handle 内部的已读位置。因此如果 actor 在 channel 之后已经更新过状态,新接收端的 has_changed() / changed() 会立刻就绪 —— 那读到的是当前值,不是“刚刚又变了一次“。

所以正确顺序是:先用 borrow() / borrow_and_update() 取初始值,再等 changed() 拿增量;别把第一次 changed() 当成一次独立的变化通知。

§actor 结束后

后台端 drop 后 sender 随之消失:changed() 返回 Err,has_changed() 返回 Err(RecvError),此时 borrow() 仍能读到最后一个值。 处理方式与 alive_rx 相同 —— Err 就是“actor 已经结束“, 不必当成致命错误。

§与 state_listen_async 的区别

state_listen_async 是回调式(每次变化 op(state).await),内部 tokio::spawn, 要求调用线程有 runtime;本方法只交出接收端,由调用方决定在哪读、多久读一次。 同步宿主或已经有自己的循环时,用这个更省事,也更好控制背压。

Source

pub fn progress_rx(&self) -> Receiver<A::Progress>

订阅进度变化,返回一个 watch::Receiver。

与 get_progress 是一对:那个是“现在多少“,这个能 “等下一次进度变化”。典型用法是进度条 / 实时指标:同步宿主每帧 has_changed() 后重绘,异步里 select! 到 rx.changed()。不需要 tokio runtime,也不自己起任务。

§语义(watch,比状态更需要小心)

进度是高频、可丢的:actor 在一帧里推进了 100 次,读者只看到最后那次。 这正适合进度条(画面本来就只能显示最新值),但如果你要的是“每个中间值都要处理“ (逐条日志、逐笔成交),那是 get_events_rx 的场景。

与 state_rx 一样,clone 出来的接收端第一次 changed() 可能立刻就绪(读到的是当前值),所以先 borrow() 拿初值再等 changed()。 actor 结束后 changed() 返回 Err,borrow() 仍能读到最后一个进度值。

§示例
let mut progress = handle.progress_rx();

if progress.has_changed().unwrap_or(false) {
    let pct: f32 = *progress.borrow_and_update();
    // set_progress_bar(pct);
}

Trait Implementations§

Source§

impl<A: ActorCore> Clone for ActorHandle<A>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<A> Forget for ActorHandle<A>

§

impl<A> Freeze for ActorHandle<A>

§

impl<A> Move for ActorHandle<A>

§

impl<A> RefUnwindSafe for ActorHandle<A>

§

impl<A> Send for ActorHandle<A>

§

impl<A> Sync for ActorHandle<A>

§

impl<A> Unpin for ActorHandle<A>

§

impl<A> UnsafeUnpin for ActorHandle<A>

§

impl<A> UnwindSafe for ActorHandle<A>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more