Ad

How To Remove A Firestore Listener In A Non-activity Class (repository Class) Android?

I have this code that gets data from Cloud Firestore:

coll_table.get().addOnCompleteListener(this, new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                MyClass obj = document.toObject(MyClass.class);
                System.out.println(obj.showDetails());
            }
        }
    }
});

When I use it in my activity class, it works fine since I can pass this to the addOnCompleteListener() function but when I move this code in a non-activity (Repository) class, it doesn't work. I read in Android docs that is not correct to use a context object in a ViewModel or in a Repository class, so how can I remove the listener in this situation?

Any help will be highly appreciated!

Ad

Answer

You don't have to pass this at all. There is an overload of addOnCompleteListener that just accepts the listener, so use that instead.

For more details with respect to dealing with listeners, you might want to look at the source code of this project to see one way to handle Firestore and Realtime Database listener with Android architecture components. Similar patterns could be applied to the result of tasks. https://github.com/CodingDoug/firebase-jetpack

Ad
source: stackoverflow.com
Ad