FerroUI/ docs

Search guides, controls, Rust APIs, and XAML.

    GitHub ↗

    use_future

    function · ferroui-view · v0.5.0

    fn use_future<D, T, F, Fut>(deps: D, make: F) -> crate::reactive::Signal<AsyncState<T>>
    where D: PartialEq + Clone + 'static,
          T: 'static,
          F: Fn(&D) -> Fut + 'static,
          Fut: Future<Output = Result<T, String>> + 'static
    

    Runs the future that make makes for deps on the dispatcher of the thread, when the component first runs and again whenever deps differ from those of the run before; the state is AsyncState::Pending until the future ends, then its value or its error. A hook: it follows the rules of the hooks.

    #[component(rerender)]
    fn Weather(city: String) -> Element {
        let forecast = use_future(city.clone(), |city| fetch_forecast(city.clone()));
        match forecast.get() {
            AsyncState::Pending => rsx! { ProgressBar { is_indeterminate: true } },
            AsyncState::Ready(forecast) => rsx! { TextBlock { text: forecast.summary } },
            AsyncState::Failed(error) => rsx! { TextBlock { text: error } },
        }
    }
    

    The future is started once the controls of the run are in place, as the closure of use_effect_with runs, with Dispatcher::start_local: it runs up to its first pending await inside that call, and every later poll is a job of the dispatcher that a wake queues, at the priority of the job that started it (DispatcherPriority::DEFAULT outside of a job). So the state is written in the job that completes the future (or in the start, for a future that does not wait), never inside the call that woke it, and behind the work of that priority queued before the wake.

    A future whose dependencies were replaced, or whose component was taken out, is aborted (JoinHandle::abort): the dispatcher drops it at once, which ends what it waited for (a sleep stops its timer), and it never writes the state, also when what it awaited completed before it was replaced. Reading the state with get() needs T: Clone; with(|state| ..) reads it in place.

    View source

    Availability

    Extracted for aarch64-apple-darwin. Cargo features are listed in the crate index.