Context

Struct Context 

Source
pub struct Context;
Expand description

A marker type for context operations.

Provides static methods for storing and retrieving context values in the reactive scope hierarchy.

§Example

let scope = Scope::new();
scope.enter(|| {
    Context::provide(42i32);
    Context::provide(String::from("Hello"));

    assert_eq!(Context::get::<i32>(), Some(42));
    assert_eq!(Context::get::<String>(), Some(String::from("Hello")));
});

Implementations§

Source§

impl Context

Source

pub fn provide<T>(value: T)
where T: Clone + 'static,

Store a context value in the current scope.

The stored context value can be retrieved by the current scope and any of its descendants using Context::get. Child scopes can provide their own values of the same type, which will shadow the parent’s value for that subtree.

Context values are automatically cleaned up when the scope is disposed.

§Example
let scope = Scope::new();
scope.enter(|| {
    Context::provide(42i32);
    assert_eq!(Context::get::<i32>(), Some(42));
});
Source

pub fn get<T>() -> Option<T>
where T: Clone + 'static,

Try to retrieve a stored context value from the current scope or its ancestors.

Context lookup walks up the scope tree from the current scope to find the nearest ancestor that provides a value of the requested type. This enables nested components to override context values for their subtrees.

§Example
let parent = Scope::new();
parent.enter(|| {
    Context::provide(42i32);

    let child = parent.create_child();
    child.enter(|| {
        // Child sees parent's context
        assert_eq!(Context::get::<i32>(), Some(42));
    });
});

Auto Trait Implementations§

Blanket Implementations§

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<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.