Struct lockjaw::Lazy[][src]

pub struct Lazy<'a, T> { /* fields omitted */ }
Expand description

Wraps a binding so it can be lazily created.

When Foo depends on Bar, Bar is created before Foo is created which may not be desirable if creating Bar is costly but it will only be used much later or only conditionally. By wrapping Bar as Lazy<Bar>, Bar will only be created when Lazy<bar>.get() is called.

Lazy.get() is cached and the same instance will be returned if called multiple times.

If multiple instances of the object is needed, use Provider<T> instead

pub struct Counter {
    counter: i32,
}

pub struct Foo {
    pub i: i32,
}

#[injectable]
impl Foo {
    #[inject]
    pub fn new(counter: &RefCell<Counter>) -> Foo{
        Foo {
            i: counter.borrow_mut().increment(),
        }
    }
}

#[component]
pub trait MyComponent {
    fn foo(&self) -> Lazy<crate::Foo>;

    fn counter(&self) -> &RefCell<Counter>;
}

pub fn main() {
    let component: Box<dyn MyComponent> = <dyn MyComponent>::new();
    let counter = component.counter();
    let lazy_foo = component.foo();
    // Foo not created yet.
    assert_eq!(counter.borrow().get(), 0);
    
    let foo = lazy_foo.get();
    assert_eq!(counter.borrow().get(), 1);

    // Same instance is reused
    let foo2 = lazy_foo.get();
    assert_eq!(foo.i, foo2.i);
}
epilogue!();

Implementations

Creates or retrieves a cached instance and returns a reference to it.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.