Skip to content

Instantly share code, notes, and snippets.

@Mindgamesnl
Last active July 24, 2023 06:48
Show Gist options
  • Save Mindgamesnl/f3dff27a88b333372cd82d2e9669717d to your computer and use it in GitHub Desktop.
Save Mindgamesnl/f3dff27a88b333372cd82d2e9669717d to your computer and use it in GitHub Desktop.
A simple bukkit datawatcher

Bukkit data watcher

A simple class to detect changing data. For example, checking if a player's location has changed every second, without needing to run code every tick or mapping data.

// setup a async datawatcher that runs every second
DataWatcher<Location> locationWatceher = new DataWatcher<>(this, false, 20);
        
// the code that the datawatcher can request a new value from
locationWatceher.setFeeder(() -> player.getLocation());
        
// setup a callback function for when the location has changed
locationWatceher.setTask((location) -> player.sendMessage("Your location has updated! to " + location));
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.function.Consumer;
public class DataWatcher<T> {
private T value;
private int task;
private Feeder<T> dataFeeder;
private Consumer<T> callback;
private Boolean isRunning = false;
public DataWatcher(JavaPlugin plugin, Boolean sync, int delayTicks) {
Runnable executor = () -> {
if (this.dataFeeder == null || this.dataFeeder == null) return;
T newValue = dataFeeder.feed();
if (this.value != null && !newValue.equals(this.value)) this.callback.accept(newValue);
this.value = newValue;
};
if (sync) {
this.task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, executor, delayTicks, delayTicks);
} else {
this.task = Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, executor, delayTicks, delayTicks);
}
isRunning = true;
}
public DataWatcher setFeeder(Feeder<T> feeder) {
this.dataFeeder = feeder;
return this;
}
public DataWatcher setTask(Consumer<T> task) {
this.callback = task;
return this;
}
public Boolean isRunning() {
return this.isRunning;
}
public void stop() {
Bukkit.getScheduler().cancelTask(this.task);
this.isRunning = false;
}
}
public interface Feeder<T> {
T feed();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment