dev.mayuna.timestop.networking.base.TimeStopResponseHandler Maven / Gradle / Ivy
package dev.mayuna.timestop.networking.base;
import dev.mayuna.timestop.networking.base.listener.TimeStopListenerManager;
import dev.mayuna.timestop.networking.base.listener.TimeStopResponseListener;
import lombok.NonNull;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
/**
* Methods for creating one time listeners
*/
public interface TimeStopResponseHandler {
/**
* Returns the listener manager
*
* @return Listener manager
*/
TimeStopListenerManager getListenerManager();
/**
* Returns the timeout timer
*
* @return Timeout timer
*/
Timer getTimeoutTimer();
/**
* Creates a one time listener for the given object and response class
*
* @param object Object
* @param responseClass Response class
* @param onResponse On response
* @param Response class type
*/
default void createOneTimeListener(Object object, Class responseClass, Consumer onResponse) {
getListenerManager().registerOneTimeListener(new TimeStopResponseListener(responseClass, 0, TimeStopResponseListener.getMessageIdIfAvailable(object)) {
@Override
public void process(@NonNull Context context, @NonNull T message) {
onResponse.accept(message);
}
});
}
/**
* Creates a one time listener for the given object and response class with a timeout
*
* @param object Object
* @param responseClass Response class
* @param timeout Timeout
* @param onResponse On response
* @param onTimeout On timeout
* @param Response class type
*/
default void createOneTimeListenerWithTimeout(Object object, Class responseClass, long timeout, Consumer onResponse, Runnable onTimeout) {
AtomicReference timeoutRunnable = new AtomicReference<>(null);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
// Will cancel the timer task and run onTimeout
timeoutRunnable.get().run();
}
};
// Create listener
TimeStopResponseListener listener = new TimeStopResponseListener(responseClass, 0, TimeStopResponseListener.getMessageIdIfAvailable(object)) {
@Override
public void process(@NonNull Context context, @NonNull T message) {
timerTask.cancel();
onResponse.accept(message);
}
};
// Set timeout runnabled
timeoutRunnable.set(() -> {
getListenerManager().unregisterListener(listener);
onTimeout.run();
});
// Schedule timer
getTimeoutTimer().schedule(timerTask, timeout);
// Register one time listener
getListenerManager().registerOneTimeListener(listener);
}
}