I've used callbacks before, but only when my client code was not responsible for keeping the program/threads running (for instance in an Android app). All I want to do now, is to make a really simple
Firestore Java client that listens for realtime database updates. My code is super simple and gives you the idea what I
want to achieve but I don't know how.
What I have tried:
public class Main {
public static void main(String[] args) {
DatabaseClient databaseClient = new DatabaseClient();
databaseClient.listenForUpdates(() -> {
System.out.println("Alright, new update, gotcha");
});
}
}
public class DatabaseClient {
private final Firestore firestore = FirestoreClient.getFirestore();
void listenForUpdates(OnUpdateListener listener) {
firestore.document("MyDocument").addSnapshotListener((value, error) -> {
listener.onUpdate();
});
}
}
public interface OnUpdateListener {
void onUpdate();
}
As expected, it now executes
run()
once and then terminates. So, how to I keep the program running so that it can receive a callback when the database is updated? I guess I could add an infinite loop, put the thread to sleep, and check for updates, but I'd like to learn how make this work using callbacks.