Firebase Android: onDataChange() event always executed in Main UI Thread?

In an Android application using Firebase, I need to execute long operations in background once Firebase returns a query answer. E.g.:

query.addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot data) {
         dosomething very long. . .
         then call a callback forUI thread
   }

I know that firebase execute the query in asynchronous mode but the onDataChange() method seems to be always executed in the main UI Thread, even if I try to call the query in a custom background Thread.

Does anyone knows how to manage this use case?


Solution 1:

The callbacks for your Firebase listeners are indeed executed on the main UI thread.

If you need to do heavy operations in a callback, spin up an AsyncTask and do the work there. The AsyncTask.doInBackground() method executes on a different thread, so it won't block the Android UI. But AsyncTask. onPostExecute() executes on the main thread again, so you can update your UI views from there.

If you're using Cloud Firestore, see Abhriya Roy's answer on how to get the callbacks on a background thread.

Solution 2:

Might be a little too late to the party, but if you want Firebase to return call backs on the background thread, you can use the BACKGROUND_EXECUTOR from com.google.firebase.firestore.util.Executors.BACKGROUND_EXECUTOR like

.addOnCompleteListener(BACKGROUND_EXECUTOR, OnCompleteListener<Void> {
   ...
}

There are other executers as well like -

DEFAULT_CALLBACK_EXECUTOR
DIRECT_EXECUTOR