Is it possible to send a synchronous request in the Firebase?
Solution 1
There is no way to synchronously load data from the Firebase Database.
While it is common for developers new to Firebase to wish for a synchronous method, it simply doesn't fit with Firebase's data synchronization model. Also see my answer here: Setting Singleton property value in Firebase Listener
Solution 2
It is not possible to load data synchronously with the official SDK. However, you can access all the data in firebase using the REST API. This would allow you to make synchronous calls. As mentioned about, Firebase is a realtime database and you will be missing the feature of updates when your data changes.
Solution 3
I made a simple class to call tasks synchronously in Android.
Note that this is similar to Javascript
's async await function.
Check my gist.
TasksManager.class
public class TasksManager {
...
public ExecutorService getExecutor() {
if (mDefaultExecutor == null || mDefaultExecutor.isShutdown() || mDefaultExecutor.isTerminated()) {
// Create a new ThreadPoolExecutor with 2 threads for each processor on the
// device and a 60 second keep-alive time.
int numCores = Runtime.getRuntime().availableProcessors();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
numCores * 2,
numCores * 2,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>()
);
mDefaultExecutor = executor;
}
return mDefaultExecutor;
}
public static <TResult> Task<TResult> call(@NonNull Callable<TResult> callable) {
return Tasks.call(getInstance().getExecutor(), callable);
}
}
Here's a sample code to use it.
TasksManager.call(() -> {
Tasks.await(AuthManager.signInAnonymously());
// You can use multiple Tasks.await method here.
// Tasks.await(getUserTask());
// Tasks.await(getProfileTask());
// Tasks.await(moreAwesomeTask());
// ...
startMainActivity();
return null;
}).addOnFailureListener(e -> {
Log.w(TAG, "signInAnonymously:ERROR", e);
});
Related videos on Youtube
Mark Korzhov
Updated on June 08, 2022Comments
-
Mark Korzhov about 2 years
I'm using
Firebase Android SDK
and became interested in sending synchronous request instead of asynchronous. According to the documentation, in any request callbacks are presented. But what about the synchronicity?Thanks!
-
Jay over 8 yearsWhy would you want to do this? The asynchronous nature of Firebase calls enables your app to account for the timing in response (amongst other things). We can probably assist more if you give us a case example.
-
Mark Korzhov over 8 years@Jay I wanted to get this information only for the sake of interest ;)
-
Alex almost 8 years
-
Richard Le Mesurier about 6 yearsParticular use-case for this requirement is receiving and processing Firebase data in the background where a permanent connection makes less sense.
-
-
CopsOnRoad over 6 yearsIt would have been better if you had provided some code.
-
Richard Le Mesurier about 6 yearsGreat tip to solving one of the challenges of working with Firebase