pub struct Resource<T> { /* private fields */ }Expand description
A value loaded on a background thread from inputs read on the main
thread. When the signals source reads change, a new load starts and the
one running is cancelled: only the newest result is ever shown, so
search-as-you-type can’t show an older query’s rows. The last value stays
readable while a new one loads.
A Copy handle, owned like a Signal: when its owner goes, the
running load is cancelled and its result dropped.
Implementations§
Source§impl<T: Clone + Send + 'static> Resource<T>
impl<T: Clone + Send + 'static> Resource<T>
Sourcepub fn new<S, E>(
source: impl Fn() -> S + 'static,
fetch: impl Fn(S, &Cancel) -> Result<T, E> + Send + Sync + 'static,
) -> Self
pub fn new<S, E>( source: impl Fn() -> S + 'static, fetch: impl Fn(S, &Cancel) -> Result<T, E> + Send + Sync + 'static, ) -> Self
Loads with fetch(source()) on a background thread, again whenever
the signals source reads change. Call from the main thread.
use ferrokit::*;
let query = Signal::new(String::new());
let matches = Resource::new(move || query.get(), |q: String, cancel: &Cancel| {
let words = std::fs::read_to_string("/usr/share/dict/words").map_err(|e| e.to_string())?;
let mut found = Vec::new();
for w in words.lines().filter(|w| w.starts_with(&q)) {
if cancel.is_cancelled() {
break; // a newer query started; this result won't be shown
}
found.push(w.to_string());
}
Ok::<_, String>(found)
});
let status = text(move || match matches.state() {
Load::Loading => "Searching…".into(),
Load::Ready(words) => format!("{} words", words.len()),
Load::Failed(e) => format!("Couldn't search: {e}"),
});Source§impl<T: Clone + 'static> Resource<T>
impl<T: Clone + 'static> Resource<T>
Sourcepub fn get(&self) -> Option<T>
pub fn get(&self) -> Option<T>
The latest loaded value (kept while a newer load runs), subscribing
the running effect. None until the first load succeeds.
Sourcepub fn get_untracked(&self) -> Option<T>
pub fn get_untracked(&self) -> Option<T>
The latest value, without subscribing (for event handlers).
Sourcepub fn with<R>(&self, f: impl FnOnce(Option<&T>) -> R) -> R
pub fn with<R>(&self, f: impl FnOnce(Option<&T>) -> R) -> R
Reads the latest value through f without copying it.