/* * Copyright (C) 2022 NotEnoughUpdates contributors * * This file is part of NotEnoughUpdates. * * NotEnoughUpdates is free software: you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * * NotEnoughUpdates is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with NotEnoughUpdates. If not, see . */ package io.github.moulberry.notenoughupdates.util; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; class AsyncDependencyLoaderImpl implements AsyncDependencyLoader { private final Supplier supplyDependency; private final Function> generator; private final BiFunction isDifferent; private volatile CompletableFuture lastValue; private volatile R lastDependency; private volatile boolean isFirstFire = true; @Override public synchronized Optional peekValue() { R nextDependency = supplyDependency.get(); if (isFirstFire || isDifferent.apply(nextDependency, lastDependency)) { isFirstFire = false; if (lastValue != null) lastValue.cancel(true); lastValue = generator.apply(nextDependency); } lastDependency = nextDependency; return Optional.ofNullable(lastValue.getNow(null)); } AsyncDependencyLoaderImpl( Supplier supplyDependency, Function> generator, BiFunction isDifferent ) { this.supplyDependency = supplyDependency; this.generator = generator; this.isDifferent = isDifferent; } }