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!
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM