0

Je connais le onDataChange() dans Firebase pour laisser dire addListenerForSingleValueEvent fonctionne sur Android Main Ui thread.Où exécutera-t-on Firebase onDataChange() dans cet exemple?

Je voulais comprendre ce qui se passera si je lance ce code à l'intérieur du ExecutorService:

runInBackground(new Runnable() { 
@Override 
public void run() { 
    ref.child("SOME_KEY") 
      .addListenerForSingleValueEvent 
        (new ValueEventListener() { 
         @Override 
         public void onDataChange(final DataSnapshot dataSnapshot) { 
          //.. do some work on Ui Thread or not?? 
         } 

         @Override 
         public void onCancelled(DatabaseError databaseError) { 
          notificationRunning = false; 
         } 
        } 
        ); 
} 
}); 
} 

Est-ce que le OnDataChange() fonctionnent toujours sur le Main Ui Enfiler Android? Et here's le coureur ExecutorService

/** 
* Submits request to be executed in background. 
* Threads submitted will be executed synchronously. 
* 
* @param runnable 
*/ 
private void runInBackground(final Runnable runnable) { 
    mBackgroundExecutor.submit(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       runnable.run(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

Et les ExecutorService

mBackgroundExecutor = Executors 
     .newSingleThreadExecutor(new ThreadFactory() { 
      @Override 
      public Thread newThread(Runnable runnable) { 
       Thread thread = new Thread(runnable, 
         "Background executor service for OneSignal"); 
       thread.setPriority(Thread.MIN_PRIORITY); 
       thread.setDaemon(true); 
       return thread; 
      } 
     }); 

Répondre

1

Les callbacks d'écoute fonctionnent toujours sur le thread principal/UI. Le thread qui a été utilisé pour ajouter l'écouteur n'affecte pas le thread de rappel. Vous pouvez le confirmer en ajoutant une instruction log à votre rappel qui renvoie le nom du thread:

Log.d(TAG, "onDataChange: Thread=" + Thread.currentThread().getName());