pub struct Lazy<'a, T> { /* private fields */ }
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§
Auto Trait Implementations§
impl<'a, T> !Freeze for Lazy<'a, T>
impl<'a, T> !RefUnwindSafe for Lazy<'a, T>
impl<'a, T> !Send for Lazy<'a, T>
impl<'a, T> !Sync for Lazy<'a, T>
impl<'a, T> Unpin for Lazy<'a, T>where
T: Unpin,
impl<'a, T> !UnwindSafe for Lazy<'a, T>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more