feature: made TaskList observable
This commit is contained in:
parent
f36826ef29
commit
c79386ec88
|
@ -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<Long, Task> taskMap = Collections.emptyMap();
|
||||
private final List<TaskListObserver> 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());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -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<Task> newTaskList);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue