package com.jozufozu.flywheel.util; import java.util.function.Consumer; import java.util.function.Supplier; import javax.annotation.Nonnull; import net.minecraftforge.common.util.NonNullSupplier; public class Lazy { private final NonNullSupplier supplier; private T value; public Lazy(NonNullSupplier supplier) { this.supplier = supplier; } @Nonnull public T get() { if (value == null) { value = supplier.get(); } return value; } /** * Provides an external facing API safe way of invalidating lazy values. */ public static Pair, KillSwitch> ofKillable(NonNullSupplier factory, Consumer destructor) { Lazy lazy = new Lazy<>(factory); KillSwitch killSwitch = new KillSwitch<>(lazy, destructor); return Pair.of(lazy, killSwitch); } public static class KillSwitch { private final Lazy lazy; private final Consumer finalizer; private KillSwitch(Lazy lazy, Consumer finalizer) { this.lazy = lazy; this.finalizer = finalizer; } public void killValue() { if (lazy.value != null) { finalizer.accept(lazy.value); lazy.value = null; } } } }