diff --git a/src/main/java/ch/zhaw/gartenverwaltung/io/JsonTaskList.java b/src/main/java/ch/zhaw/gartenverwaltung/io/JsonTaskList.java index 6b18f72..7f6d36b 100644 --- a/src/main/java/ch/zhaw/gartenverwaltung/io/JsonTaskList.java +++ b/src/main/java/ch/zhaw/gartenverwaltung/io/JsonTaskList.java @@ -13,6 +13,7 @@ import java.net.URISyntaxException; import java.net.URL; import java.time.LocalDate; import java.time.format.DateTimeFormatter; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -29,6 +30,7 @@ public class JsonTaskList implements TaskList { private final static String INVALID_DATASOURCE_MSG = "Invalid datasource specified!"; private Map taskMap = Collections.emptyMap(); + private final List subscribers = new ArrayList<>(); /** * Creating constant objects required to deserialize the {@link LocalDate} classes @@ -87,6 +89,7 @@ public class JsonTaskList implements TaskList { loadTaskListFromFile(); } taskMap.values().removeIf(task -> task.getCropId() == cropId); + notifySubscribers(); } /** @@ -107,6 +110,7 @@ public class JsonTaskList implements TaskList { taskMap.put(id, task.withId(id)); writeTaskListToFile(); + notifySubscribers(); } /** @@ -126,6 +130,25 @@ public class JsonTaskList implements TaskList { taskMap.remove(taskId); writeTaskListToFile(); } + notifySubscribers(); + } + + /** + * {@inheritDoc} + * @param observer The change handler + */ + @Override + public void subscribe(TaskListObserver observer) { + subscribers.add(observer); + } + + /** + * Calls the change handler method on all registered observers. + */ + private void notifySubscribers() { + for (TaskListObserver subscriber : subscribers) { + subscriber.onChange(taskMap.values().stream().toList()); + } } /** diff --git a/src/main/java/ch/zhaw/gartenverwaltung/io/TaskList.java b/src/main/java/ch/zhaw/gartenverwaltung/io/TaskList.java index 97ef3a7..95f5b07 100644 --- a/src/main/java/ch/zhaw/gartenverwaltung/io/TaskList.java +++ b/src/main/java/ch/zhaw/gartenverwaltung/io/TaskList.java @@ -51,4 +51,22 @@ public interface TaskList { * @throws IOException If the database cannot be accessed */ void removeTask(Task task) throws IOException; + + /** + * Registers an observer to be notified of Changes in the TaskList + * @param observer The change handler + */ + void subscribe(TaskListObserver observer); + + /** + * Specifies an observer for a TaskList + */ + @FunctionalInterface + interface TaskListObserver { + /** + * Method which will be called when changes occur. + * @param newTaskList The new values + */ + void onChange(List newTaskList); + } }