mirror of
https://github.com/Jozufozu/Flywheel.git
synced 2025-01-09 22:06:09 +01:00
dfbba8e3d0
- Might have bumped the version too early. - Fix crash rendering breaking overlay after reloading resource packs.
57 lines
1.1 KiB
Java
57 lines
1.1 KiB
Java
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<T> {
|
|
|
|
private final NonNullSupplier<T> supplier;
|
|
|
|
private T value;
|
|
|
|
public Lazy(NonNullSupplier<T> 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 <T> Pair<Lazy<T>, KillSwitch<T>> ofKillable(NonNullSupplier<T> factory, Consumer<T> destructor) {
|
|
Lazy<T> lazy = new Lazy<>(factory);
|
|
|
|
KillSwitch<T> killSwitch = new KillSwitch<>(lazy, destructor);
|
|
|
|
return Pair.of(lazy, killSwitch);
|
|
}
|
|
|
|
public static class KillSwitch<T> {
|
|
|
|
private final Lazy<T> lazy;
|
|
private final Consumer<T> finalizer;
|
|
|
|
private KillSwitch(Lazy<T> lazy, Consumer<T> finalizer) {
|
|
this.lazy = lazy;
|
|
this.finalizer = finalizer;
|
|
}
|
|
|
|
public void killValue() {
|
|
if (lazy.value != null) {
|
|
finalizer.accept(lazy.value);
|
|
lazy.value = null;
|
|
}
|
|
}
|
|
}
|
|
}
|