Skip to main content

KeyedRequests

Struct KeyedRequests 

Source
pub struct KeyedRequests<K> { /* private fields */ }
Available on crate feature web03 only.
Expand description

A set of pending requests with at most one for each key, kept alive until each completes.

This is like Requests, except that each request is stored under a key with KeyedRequests::insert. Storing a request under a key which already has one cancels the request stored before it, so that what is fetched for a key is always the latest. Any number of keys can have a request in flight at once, and a key is forgotten once its request completes.

Every request still pending is cancelled when the set is dropped or cleared.

§Examples

use yew::prelude::*;
use musli_web::web03::prelude::*;

mod api {
    use musli::{Decode, Encode};
    use musli_web::api;

    #[derive(Encode, Decode)]
    pub struct RenameRequest<'de> {
        pub id: u32,
        pub name: &'de str,
    }

    api::define! {
        pub type Rename;

        impl Endpoint for Rename {
            impl<'de> Request for RenameRequest<'de>;
            type Response<'de> = ();
        }
    }
}

enum Msg {
    Rename(u32, String),
    Renamed(Result<ws::Packet<api::Rename>, ws::Error>),
}

#[derive(Properties, PartialEq)]
struct Props {
    ws: ws::Handle,
    rows: Vec<u32>,
}

struct Rows {
    // At most one rename in flight for each row.
    renames: ws::KeyedRequests<u32>,
}

impl Component for Rows {
    type Message = Msg;
    type Properties = Props;

    fn create(_: &Context<Self>) -> Self {
        Self {
            renames: ws::KeyedRequests::new(),
        }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            Msg::Rename(id, name) => {
                // Renaming a row again cancels its earlier rename, but
                // leaves the renames of other rows alone.
                self.renames.insert(
                    id,
                    ctx.props()
                        .ws
                        .request()
                        .body(api::RenameRequest { id, name: &name })
                        .on_packet(ctx.link().callback(Msg::Renamed))
                        .send(),
                );

                true
            }
            Msg::Renamed(_) => true,
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        html! {
            {for ctx.props().rows.iter().copied().map(|id| {
                let onclick = ctx.link().callback(move |_: MouseEvent| {
                    Msg::Rename(id, format!("Row {id}"))
                });

                let label = if self.renames.is_pending(&id) {
                    String::from("Renaming...")
                } else {
                    format!("Rename #{id}")
                };

                html!(<button {onclick}>{label}</button>)
            })}
        }
    }
}

Implementations§

Source§

impl<K> KeyedRequests<K>

Source

pub fn new() -> Self

Construct an empty set of requests.

§Examples
use musli_web::web03::prelude::*;

let requests = ws::KeyedRequests::<u32>::new();
assert!(requests.is_empty());
Source

pub fn len(&self) -> usize

The number of keys whose request is still pending.

Source

pub fn is_empty(&self) -> bool

Whether no request is pending.

Source

pub fn keys(&self) -> impl Iterator<Item = &K>

Iterate over the keys whose request is still pending, in no particular order.

Source

pub fn clear(&mut self)

Cancel every pending request.

Source§

impl<K> KeyedRequests<K>
where K: Eq + Hash,

Source

pub fn insert(&mut self, key: K, request: Request)

Keep request under key until it completes, cancelling the request stored under key before it.

A request which is not pending, such as one which could not be sent, is dropped straight away, but still cancels the one before it.

Source

pub fn remove<Q>(&mut self, key: &Q) -> bool
where K: Borrow<Q>, Q: ?Sized + Eq + Hash,

Cancel the request stored under key, returning whether it was still pending.

Source

pub fn is_pending<Q>(&self, key: &Q) -> bool
where K: Borrow<Q>, Q: ?Sized + Eq + Hash,

Whether the request stored under key is still pending.

Trait Implementations§

Source§

impl<K> Debug for KeyedRequests<K>
where K: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<K> Default for KeyedRequests<K>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<K> !RefUnwindSafe for KeyedRequests<K>

§

impl<K> !Send for KeyedRequests<K>

§

impl<K> !Sync for KeyedRequests<K>

§

impl<K> !UnwindSafe for KeyedRequests<K>

§

impl<K> Freeze for KeyedRequests<K>
where HashMap<K, Request>: Freeze,

§

impl<K> Unpin for KeyedRequests<K>
where HashMap<K, Request>: Unpin,

§

impl<K> UnsafeUnpin for KeyedRequests<K>

Blanket Implementations§

Source§

impl<Token, Builder, How> AllPropsFor<Builder, How> for Token
where Builder: Buildable<Token>, <Builder as Buildable<Token>>::WrappedToken: HasAllProps<<Builder as Buildable<Token>>::Output, How>,

Source§

impl<Token, Builder, How> AllPropsFor<Builder, How> for Token
where Builder: Buildable<Token>, <Builder as Buildable<Token>>::WrappedToken: HasAllProps<<Builder as Buildable<Token>>::Output, How>,

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> HasAllProps<(), T> for T

Source§

impl<T> HasAllProps<(), T> for T

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoPropValue<Option<T>> for T

Source§

fn into_prop_value(self) -> Option<T>

Convert self to a value of a Properties struct.
Source§

impl<T> IntoPropValue<Option<T>> for T

Source§

fn into_prop_value(self) -> Option<T>

Convert self to a value of a Properties struct.
Source§

impl<T> IntoPropValue<T> for T

Source§

fn into_prop_value(self) -> T

Convert self to a value of a Properties struct.
Source§

impl<T> IntoPropValue<T> for T

Source§

fn into_prop_value(self) -> T

Convert self to a value of a Properties struct.
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more