Asynchronous Worker in Android WorkManager

Anton Tananaev picture Anton Tananaev · May 18, 2018 · Viewed 19.4k times · Source

Google recently announced new WorkManager architecture component. It makes it easy to schedule synchronous work by implementing doWork() in Worker class, but what if I want to do some asynchronous work in the background? For example, I want to make a network service call using Retrofit. I know I can make a synchronous network request, but it would block the thread and just feels wrong. Is there any solution for this or it is just not supported at the moment?

Answer

TomH picture TomH · May 19, 2018

I used a countdownlatch and waited for this to reach 0, which will only happen once the asynchronous callback has updated it. See this code:

public WorkerResult doWork() {

        final WorkerResult[] result = {WorkerResult.RETRY};
        CountDownLatch countDownLatch = new CountDownLatch(1);
        FirebaseFirestore db = FirebaseFirestore.getInstance();

        db.collection("collection").whereEqualTo("this","that").get().addOnCompleteListener(task -> {
            if(task.isSuccessful()) {
                task.getResult().getDocuments().get(0).getReference().update("field", "value")
                        .addOnCompleteListener(task2 -> {
                            if (task2.isSuccessful()) {
                                result[0] = WorkerResult.SUCCESS;
                            } else {
                                result[0] = WorkerResult.RETRY;
                            }
                            countDownLatch.countDown();
                        });
            } else {
                result[0] = WorkerResult.RETRY;
                countDownLatch.countDown();
            }
        });

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return result[0];

    }