Ad

Obtaining And Storing A Firestore Instance In A Long Running Service

- 1 answer

I have a static utility class which makes use of Firestore. The database operations are invoked occasionally by a background service. I expect this service to run for months on the user's phone.

I've been initializing an instance of Firestore in a static variable and using that throughout. Are there any bad effects of keeping an instance alive this way?

Is it better to call getInstance every time I need it? It seems like Firestore caches the result of getInstance.

class FSWrapper {

   private static FirebaseFirestore fs = FirebaseFirestore.getInstance();

   public static operation1() {
       // do some reads
   }

   public static operation2() {
       // do some writes
   }
}


class BackgroundService extends Service {
    public void onSomeEvent() {
        FSWrapper.operation1();
        FSWrapper.operation2();
        .....
    }
}
Ad

Answer

FirebaseFirestore.getInstance() returns a singleton object, the same object every time. It's never going to get garbage collected, so you can hold it for as long as you want anywhere you want with no downside (other than not being able to unit test with it correctly - you would want to inject the singleton some other way to do that).

Ad
source: stackoverflow.com
Ad