Function getWritableLazy

  • Create and return a writable ILazyValue instance which will cache and return the value returned by the callback function. The callback function will only be called once, multiple access of the value does not cause re-execution of the callback as the result from the first call is cached internally. The value may be set as many times as required, if the callback has not been called when you set the value it will never get called.

    Type Parameters

    • T

    Parameters

    • cb: (() => T)

      The callback function to fetch the value to be lazily evaluated and cached

        • (): T
        • Returns T

    Returns ILazyValue<T>

    A new writable ILazyValue instance which wraps the callback and will be used to cache the result of the callback

    0.11.7

    // This does not cause the evaluation to occur
    let cachedValue = getWritableLazy(() => callSomeExpensiveFunction());
    let theValue;

    // Just checking if there is an object still does not cause the evaluation
    if (cachedValue) {
    // This will cause the evaluation to occur and the result will be cached
    theValue = cachedValue.v;
    }

    // Accessing the value again will not cause the re-evaluation to occur, it will just return the same
    // result value again.
    theValue === cachedValue.v; // true

    // Setting the value
    let cachedValue = getWritableLazy(() => callSomeExpensiveFunction());
    let theValue = "new Value";

    // Just checking if there is an object still does not cause the evaluation
    if (cachedValue) {
    // This will set the value to be set explicitly and the callback
    // will now never occur and the result will be cached
    cachedValue.v = theValue;
    }

    // Accessing the value again will cause the previously set value to be returned.
    theValue === cachedValue.v; // true