Skip to content

Feature request: lazy Val/Var #57

@Grannath

Description

@Grannath

Hi,

I'm thinking about an extension to Val/Var, or rather to the provided factory methods. The idea is to provide a Supplier that gets called the first time the value is actually read.

Val<String> lazyVal = Val.lazy(this::calculateComplicatedName); // not called yet
// do some stuff
System.out.println(lazyVal.getValue()); // calculateComplicatedName called now
System.out.println(lazyVal.getValue()); // result was cached, not called again

This is obviously useful for cases where a default value is expensive to calculate. But I was actually thinking about loading remote values on demand. Instead of loading everythink immediately, this would provide a clean API for lazy loading. For remote calls, this would have to be done async.

Val<String> lazyVal = Val.lazyAsync(String placeholder, this::loadNameFromServer); // not called yet
// do some stuff
System.out.println(lazyVal.getValue()); // returns placeholder, loadNameFromServer started in separate thread
// some time later
System.out.println(lazyVal.getValue()); // loading was finished, returns result now

While it's easy enough for a Val, because it cannot change, I'm not so sure how or even if it's useful for a Var. But I would be grateful for any input on this. If there is interest, I would be happy to code it myself and start a pull request.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions