package me.clip.placeholderapi.util; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; public final class Futures { private Futures() {} public static void onMainThread(@NotNull final Plugin plugin, @NotNull final CompletableFuture future, @NotNull final BiConsumer consumer) { future.whenComplete((value, exception) -> { if (Bukkit.isPrimaryThread()) { consumer.accept(value, exception); } else { Bukkit.getScheduler().runTask(plugin, () -> consumer.accept(value, exception)); } }); } @NotNull public static Collector, ?, CompletableFuture>> collector() { return Collectors.collectingAndThen(Collectors.toList(), Futures::of); } @NotNull public static CompletableFuture> of(@NotNull final Stream> futures) { return of(futures.collect(Collectors.toList())); } @NotNull public static CompletableFuture> of(@NotNull final Collection> futures) { return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) .thenApplyAsync($ -> awaitCompletion(futures)); } @NotNull private static List awaitCompletion(@NotNull final Collection> futures) { return futures.stream().map(CompletableFuture::join).collect(Collectors.toList()); } }