Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

Java
public class Main {

    public static void main(String[] args) {
        DatabaseClient databaseClient = new DatabaseClient();
        databaseClient.listenForUpdates(() -> {
            System.out.println("Alright, new update, gotcha");
        });
    }
}
Java
public class DatabaseClient {

    private final Firestore firestore = FirestoreClient.getFirestore();

    void listenForUpdates(OnUpdateListener listener) {
        firestore.document("MyDocument").addSnapshotListener((value, error) -> {
            //Ignore 'value' and 'error' in this example
            listener.onUpdate();
        });
    }
}
Java
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.
Posted
Comments
[no name] 20-Apr-20 17:15pm    
There's always a "loop" or a while somewhere. In Windows, it's the "message loop". In a console app, you make your own. Since asynch is pointless without "other work" to do in the meantime, you make it synchronous with a timeout mechanism.
VanuDiplomat 20-Apr-20 17:22pm    
Thanks, that makes sense. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900