use_future works
This commit is contained in:
5 files changed
+76
-42
No files matched your search
+2
-2
@@ -7,7 +7,7 @@ fn main() {
|
|||||||
|
|
||||||
fn app() -> Element {
|
fn app() -> Element {
|
||||||
let mut breed = use_signal(|| "deerhound".to_string());
|
let mut breed = use_signal(|| "deerhound".to_string());
|
||||||
let breed_list = use_resource(|| async move {
|
let breed_list = use_resource(move || async move {
|
||||||
let list = reqwest::get("https://dog.ceo/api/breeds/list/all")
|
let list = reqwest::get("https://dog.ceo/api/breeds/list/all")
|
||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -44,7 +44,7 @@ fn app() -> Element {
|
|||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
fn BreedPic(breed: Signal<String>) -> Element {
|
fn BreedPic(breed: Signal<String>) -> Element {
|
||||||
let fut = use_resource(|| async move {
|
let fut = use_resource(move || async move {
|
||||||
reqwest::get(format!("https://dog.ceo/api/breed/{breed}/images/random"))
|
reqwest::get(format!("https://dog.ceo/api/breed/{breed}/images/random"))
|
||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn app() -> Element {
|
fn app() -> Element {
|
||||||
let future = use_resource(|| async move {
|
let future = use_resource(move || async move {
|
||||||
let mut eval = eval(
|
let mut eval = eval(
|
||||||
r#"
|
r#"
|
||||||
dioxus.send("Hi from JS!");
|
dioxus.send("Hi from JS!");
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ impl<O: 'static + ?Sized> Clone for UseCallback<O> {
|
|||||||
Self { inner: self.inner }
|
Self { inner: self.inner }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// impl<O: 'static> Copy for UseCallback<O> {}
|
impl<O: 'static> Copy for UseCallback<O> {}
|
||||||
|
|
||||||
impl<O> UseCallback<O> {
|
impl<O> UseCallback<O> {
|
||||||
/// Call the callback
|
/// Call the callback
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
#![allow(missing_docs)]
|
#![allow(missing_docs)]
|
||||||
use crate::{use_callback, use_hook_did_run, use_signal};
|
use crate::{use_callback, use_hook_did_run, use_signal, UseCallback};
|
||||||
use dioxus_core::{
|
use dioxus_core::{
|
||||||
prelude::{spawn, use_drop, use_hook},
|
prelude::{flush_sync, spawn, use_drop, use_hook},
|
||||||
Task,
|
Task,
|
||||||
};
|
};
|
||||||
use dioxus_signals::*;
|
use dioxus_signals::*;
|
||||||
@@ -10,22 +10,30 @@ use std::future::Future;
|
|||||||
|
|
||||||
/// A hook that allows you to spawn a future
|
/// A hook that allows you to spawn a future
|
||||||
///
|
///
|
||||||
/// Does not regenerate the future when dependencies change.
|
/// The future is spawned on the next call to `flush_sync` which means that it will not run on the server.
|
||||||
pub fn use_future<F>(future: impl FnMut() -> F + 'static) -> UseFuture
|
/// To run a future on the server, you should use `spawn` directly.
|
||||||
|
pub fn use_future<F>(mut future: impl FnMut() -> F + 'static) -> UseFuture
|
||||||
where
|
where
|
||||||
F: Future + 'static,
|
F: Future + 'static,
|
||||||
{
|
{
|
||||||
let mut callback = use_callback(future);
|
let mut complete = use_signal(|| UseFutureState::Pending);
|
||||||
let mut state = use_signal(|| UseFutureState::Pending);
|
|
||||||
|
let mut callback = use_callback(move || {
|
||||||
|
let fut = future();
|
||||||
|
spawn(async move {
|
||||||
|
// todo: not sure if we should flush_sync
|
||||||
|
// It's fine for most cases but means that the future will always be started in the next frame
|
||||||
|
// The point here is to not run use_future on the server... which like, shouldn't we?
|
||||||
|
flush_sync().await;
|
||||||
|
|
||||||
|
complete.set(UseFutureState::Pending);
|
||||||
|
fut.await;
|
||||||
|
complete.set(UseFutureState::Complete);
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
// Create the task inside a copyvalue so we can reset it in-place later
|
// Create the task inside a copyvalue so we can reset it in-place later
|
||||||
let task = use_hook(|| {
|
let task = use_hook(|| CopyValue::new(callback.call()));
|
||||||
let fut = callback.call();
|
|
||||||
CopyValue::new(spawn(async move {
|
|
||||||
fut.await;
|
|
||||||
state.set(UseFutureState::Complete);
|
|
||||||
}))
|
|
||||||
});
|
|
||||||
|
|
||||||
// Early returns in dioxus have consequences for use_memo, use_resource, and use_future, etc
|
// Early returns in dioxus have consequences for use_memo, use_resource, and use_future, etc
|
||||||
// We *don't* want futures to be running if the component early returns. It's a rather weird behavior to have
|
// We *don't* want futures to be running if the component early returns. It's a rather weird behavior to have
|
||||||
@@ -40,13 +48,18 @@ where
|
|||||||
|
|
||||||
use_drop(move || task.peek().stop());
|
use_drop(move || task.peek().stop());
|
||||||
|
|
||||||
UseFuture { task, state }
|
UseFuture {
|
||||||
|
task,
|
||||||
|
state: complete,
|
||||||
|
callback,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(unused)]
|
#[derive(Clone, Copy)]
|
||||||
pub struct UseFuture {
|
pub struct UseFuture {
|
||||||
task: CopyValue<Task>,
|
task: CopyValue<Task>,
|
||||||
state: Signal<UseFutureState>,
|
state: Signal<UseFutureState>,
|
||||||
|
callback: UseCallback<Task>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UseFuture {
|
impl UseFuture {
|
||||||
@@ -54,43 +67,64 @@ impl UseFuture {
|
|||||||
///
|
///
|
||||||
/// Will not cancel the previous future, but will ignore any values that it
|
/// Will not cancel the previous future, but will ignore any values that it
|
||||||
/// generates.
|
/// generates.
|
||||||
pub fn restart(&self) {
|
pub fn restart(&mut self) {
|
||||||
// self.needs_regen.set(true);
|
self.task.write().stop();
|
||||||
// (self.update)();
|
let new_task = self.callback.call();
|
||||||
|
self.task.set(new_task);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Forcefully cancel a future
|
/// Forcefully cancel a future
|
||||||
pub fn cancel(&mut self) {
|
pub fn cancel(&mut self) {
|
||||||
|
self.state.set(UseFutureState::Stopped);
|
||||||
self.task.write().stop();
|
self.task.write().stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the ID of the future in Dioxus' internal scheduler
|
/// Pause the future
|
||||||
pub fn task(&self) -> Option<Task> {
|
pub fn pause(&mut self) {
|
||||||
todo!()
|
self.state.set(UseFutureState::Paused);
|
||||||
// self.task.get()
|
self.task.write().pause();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resume the future
|
||||||
|
pub fn resume(&mut self) {
|
||||||
|
if self.finished() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.state.set(UseFutureState::Pending);
|
||||||
|
self.task.write().resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get a handle to the inner task backing this future
|
||||||
|
/// Modify the task through this handle will cause inconsistent state
|
||||||
|
pub fn task(&self) -> Task {
|
||||||
|
self.task.cloned()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the current state of the future.
|
/// Get the current state of the future.
|
||||||
pub fn state(&self) -> UseFutureState {
|
pub fn finished(&self) -> bool {
|
||||||
todo!()
|
matches!(self.state.peek().clone(), UseFutureState::Complete)
|
||||||
// match (&self.task.get(), &self.value()) {
|
}
|
||||||
// // If we have a task and an existing value, we're reloading
|
|
||||||
// (Some(_), Some(val)) => UseFutureState::Reloading(val),
|
|
||||||
|
|
||||||
// // no task, but value - we're done
|
/// Get the current state of the future.
|
||||||
// (None, Some(val)) => UseFutureState::Complete(val),
|
pub fn state(&self) -> ReadOnlySignal<UseFutureState> {
|
||||||
|
self.state.clone().into()
|
||||||
// // no task, no value - something's wrong? return pending
|
|
||||||
// (None, None) => UseFutureState::Pending,
|
|
||||||
|
|
||||||
// // Task, no value - we're still pending
|
|
||||||
// (Some(_), None) => UseFutureState::Pending,
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A signal that represents the state of a future
|
||||||
|
// we might add more states (panicked, etc)
|
||||||
|
#[derive(Clone, Copy, PartialEq, Hash, Eq, Debug)]
|
||||||
pub enum UseFutureState {
|
pub enum UseFutureState {
|
||||||
|
/// The future is still running
|
||||||
Pending,
|
Pending,
|
||||||
|
|
||||||
|
/// The future has been forcefully stopped
|
||||||
|
Stopped,
|
||||||
|
|
||||||
|
/// The future has been paused, tempoarily
|
||||||
|
Paused,
|
||||||
|
|
||||||
|
/// The future has completed
|
||||||
Complete,
|
Complete,
|
||||||
Regenerating, // the old value
|
|
||||||
}
|
}
|
||||||
@@ -19,7 +19,7 @@ use std::future::Future;
|
|||||||
/// will be canceled before the new one is started.
|
/// will be canceled before the new one is started.
|
||||||
///
|
///
|
||||||
/// - dependencies: a tuple of references to values that are PartialEq + Clone
|
/// - dependencies: a tuple of references to values that are PartialEq + Clone
|
||||||
pub fn use_resource<T, F>(future: impl Fn() -> F) -> UseResource<T>
|
pub fn use_resource<T, F>(future: impl Fn() -> F + 'static) -> UseResource<T>
|
||||||
where
|
where
|
||||||
T: 'static,
|
T: 'static,
|
||||||
F: Future<Output = T> + 'static,
|
F: Future<Output = T> + 'static,
|
||||||
|
|||||||
Reference in new issue
Block a user