Skip to main content

WritableUtils

Trait WritableUtils 

Source
pub trait WritableUtils<T: 'static> {
    // Required methods
    fn write_state(&mut self) -> WriteRef<'static, T>;
    fn peek_state(&self) -> ReadRef<'static, T>;

    // Provided methods
    fn set(&mut self, value: T) { ... }
    fn set_if_modified(&mut self, value: T)
       where T: PartialEq { ... }
    fn set_if_modified_and_then(&mut self, value: T, then: impl FnOnce())
       where T: PartialEq { ... }
    fn with_mut(&mut self, with: impl FnOnce(WriteRef<'static, T>)) { ... }
}
Expand description

A shared interface for types that provide reactive write access to a value of type T.

Implementors must provide WritableUtils::write_state and WritableUtils::peek_state. All convenience methods (WritableUtils::set, WritableUtils::set_if_modified, etc.) are provided as defaults.

Required Methods§

Source

fn write_state(&mut self) -> WriteRef<'static, T>

Get a mutable reference to the value, notifying subscribers.

Source

fn peek_state(&self) -> ReadRef<'static, T>

Read the current value without subscribing to changes.

Provided Methods§

Source

fn set(&mut self, value: T)

Replace the current value and notify subscribers.

§Example
let mut status = use_state(|| "idle");

status.set("loading");
status.set("complete");
Source

fn set_if_modified(&mut self, value: T)
where T: PartialEq,

Replace the value only if it differs from the current one.

This prevents unnecessary re-renders when setting the same value repeatedly.

§Example
let mut count = use_state(|| 0);

// This will update and notify subscribers
count.set_if_modified(5);

// This will do nothing (value is already 5)
count.set_if_modified(5);
Source

fn set_if_modified_and_then(&mut self, value: T, then: impl FnOnce())
where T: PartialEq,

Replace the value if modified, then run a callback.

§Example
let mut score = use_state(|| 0);

score.set_if_modified_and_then(100, || {
    println!("High score achieved!");
});
Source

fn with_mut(&mut self, with: impl FnOnce(WriteRef<'static, T>))

Modify the value via a closure with a single notification.

§Example
let mut counter = use_state(|| 0);

counter.with_mut(|mut value| {
    *value += 1;
    *value *= 2;
});

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<T: 'static> WritableUtils<T> for State<T>

Source§

impl<T: 'static> WritableUtils<T> for Writable<T>