feature: made TaskList observable

This commit is contained in:
David Guler 2022-11-25 20:03:32 +01:00
parent f36826ef29
commit c79386ec88
2 changed files with 41 additions and 0 deletions

View File

@ -13,6 +13,7 @@ import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -29,6 +30,7 @@ public class JsonTaskList implements TaskList {
private final static String INVALID_DATASOURCE_MSG = "Invalid datasource specified!"; private final static String INVALID_DATASOURCE_MSG = "Invalid datasource specified!";
private Map<Long, Task> taskMap = Collections.emptyMap(); private Map<Long, Task> taskMap = Collections.emptyMap();
private final List<TaskListObserver> subscribers = new ArrayList<>();
/** /**
* Creating constant objects required to deserialize the {@link LocalDate} classes * Creating constant objects required to deserialize the {@link LocalDate} classes
@ -87,6 +89,7 @@ public class JsonTaskList implements TaskList {
loadTaskListFromFile(); loadTaskListFromFile();
} }
taskMap.values().removeIf(task -> task.getCropId() == cropId); taskMap.values().removeIf(task -> task.getCropId() == cropId);
notifySubscribers();
} }
/** /**
@ -107,6 +110,7 @@ public class JsonTaskList implements TaskList {
taskMap.put(id, task.withId(id)); taskMap.put(id, task.withId(id));
writeTaskListToFile(); writeTaskListToFile();
notifySubscribers();
} }
/** /**
@ -126,6 +130,25 @@ public class JsonTaskList implements TaskList {
taskMap.remove(taskId); taskMap.remove(taskId);
writeTaskListToFile(); 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());
}
} }
/** /**

View File

@ -51,4 +51,22 @@ public interface TaskList {
* @throws IOException If the database cannot be accessed * @throws IOException If the database cannot be accessed
*/ */
void removeTask(Task task) throws IOException; 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<Task> newTaskList);
}
} }