pub struct Resource<T, E = String>where
T: 'static,
E: 'static,{ /* private fields */ }Expand description
异步加载的数据:依赖变了自动重新加载,加载中、数据、错误都是响应式的,直接绑定到界面上。
let id = signal(1);
let user = resource(move || id.get(), |id| async move { fetch_user(id).await });
text(move || match (user.get(), user.error()) {
(_, Some(error)) => format!("出错了:{error}"),
(Some(name), _) => name,
(None, _) => "加载中…".into(),
})
.opacity(move || if user.is_loading() { 0.5 } else { 1.0 });和 resource 一起看:
source在副作用里执行,读到的信号就是依赖;依赖变了就用新值调用fetcher。fetcher在主线程调用(不追踪依赖),返回的 future 在后台线程池上运行(必须是Send),结果交回主线程。- 竞态安全:依赖变化或
Resource::refetch时,上一次还没完成的请求被取消(future 被丢弃), 晚到的旧结果不会覆盖新结果。 - 加载新数据期间
Resource::get仍是上一次成功的结果(界面不闪),用Resource::is_loading显示加载状态; 失败时Resource::error有值,数据保留上一次成功的;之后成功时清掉错误。 - 归创建时的作用域所有:作用域释放(比如元素卸载)时取消进行中的请求。
fetcher返回的 future panic 时只结束加载状态(panic 信息打印在终端),不影响界面
Implementations§
Trait Implementations§
Auto Trait Implementations§
impl<T, E = String> !Send for Resource<T, E>
impl<T, E = String> !Sync for Resource<T, E>
impl<T, E> Forget for Resource<T, E>
impl<T, E> Freeze for Resource<T, E>
impl<T, E> RefUnwindSafe for Resource<T, E>
impl<T, E> Unpin for Resource<T, E>
impl<T, E> UnsafeUnpin for Resource<T, E>
impl<T, E> UnwindSafe for Resource<T, E>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Convert
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can
then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Convert
Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be
further downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
Convert
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
Convert
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.