Is it possible to send a synchronous request in the Firebase?

前端 未结 4 1440
无人共我
无人共我 2020-12-17 10:51

I\'m using Firebase Android SDK and became interested in sending synchronous request instead of asynchronous. According to the documentation, in any request cal

4条回答
  •  醉话见心
    2020-12-17 11:25

    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  Task call(@NonNull Callable 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);
    });
    

提交回复
热议问题