feat: overhaul examples and clean things up
This commit is contained in:
1 parent
601632fc7e
commit
420a30e5d4
33 files changed
+1089
-1417
No files matched your search
@@ -3,27 +3,16 @@ use std::{cell::Cell, future::Future, rc::Rc};
|
||||
|
||||
pub fn use_future<'a, T: 'static, F: Future<Output = T> + 'static>(
|
||||
cx: &'a ScopeState,
|
||||
f: impl FnOnce() -> F,
|
||||
) -> (Option<&T>, FutureHandle<'a, T>) {
|
||||
let state = cx.use_hook(|_| {
|
||||
new_fut: impl FnOnce() -> F,
|
||||
) -> &'a UseFuture<T> {
|
||||
let state = cx.use_hook(move |_| {
|
||||
//
|
||||
let fut = f();
|
||||
let slot = Rc::new(Cell::new(None));
|
||||
let updater = cx.schedule_update();
|
||||
|
||||
let _slot = slot.clone();
|
||||
let new_fut = async move {
|
||||
let res = fut.await;
|
||||
_slot.set(Some(res));
|
||||
updater();
|
||||
};
|
||||
let task = cx.push_future(new_fut);
|
||||
|
||||
UseFutureInner {
|
||||
needs_regen: true,
|
||||
slot,
|
||||
UseFuture {
|
||||
update: cx.schedule_update(),
|
||||
needs_regen: Cell::new(true),
|
||||
slot: Rc::new(Cell::new(None)),
|
||||
value: None,
|
||||
task: Some(task),
|
||||
task: None,
|
||||
}
|
||||
});
|
||||
|
||||
@@ -32,23 +21,55 @@ pub fn use_future<'a, T: 'static, F: Future<Output = T> + 'static>(
|
||||
state.task = None;
|
||||
}
|
||||
|
||||
(
|
||||
state.value.as_ref(),
|
||||
FutureHandle {
|
||||
cx,
|
||||
value: Cell::new(None),
|
||||
},
|
||||
)
|
||||
if state.needs_regen.get() {
|
||||
// We don't need regen anymore
|
||||
state.needs_regen.set(false);
|
||||
|
||||
// Create the new future
|
||||
let fut = new_fut();
|
||||
|
||||
// Clone in our cells
|
||||
let slot = state.slot.clone();
|
||||
let updater = state.update.clone();
|
||||
|
||||
state.task = Some(cx.push_future(async move {
|
||||
let res = fut.await;
|
||||
slot.set(Some(res));
|
||||
updater();
|
||||
}));
|
||||
}
|
||||
|
||||
state
|
||||
}
|
||||
|
||||
struct UseFutureInner<T> {
|
||||
needs_regen: bool,
|
||||
pub struct UseFuture<T> {
|
||||
update: Rc<dyn Fn()>,
|
||||
needs_regen: Cell<bool>,
|
||||
value: Option<T>,
|
||||
slot: Rc<Cell<Option<T>>>,
|
||||
task: Option<TaskId>,
|
||||
}
|
||||
|
||||
pub struct FutureHandle<'a, T> {
|
||||
cx: &'a ScopeState,
|
||||
value: Cell<Option<T>>,
|
||||
impl<T> UseFuture<T> {
|
||||
pub fn restart(&self) {
|
||||
self.needs_regen.set(true);
|
||||
(self.update)();
|
||||
}
|
||||
|
||||
// clears the value in the future slot without starting the future over
|
||||
pub fn clear(&self) -> Option<T> {
|
||||
(self.update)();
|
||||
self.slot.replace(None)
|
||||
}
|
||||
|
||||
// Manually set the value in the future slot without starting the future over
|
||||
pub fn set(&self, new_value: T) {
|
||||
self.slot.set(Some(new_value));
|
||||
self.needs_regen.set(true);
|
||||
(self.update)();
|
||||
}
|
||||
|
||||
pub fn value(&self) -> Option<&T> {
|
||||
self.value.as_ref()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user