DEV Community

BalaKrishnan
BalaKrishnan

Posted on

1 1

RxJava - Make your Async Task Synchronous

In Android framework, We have to do all the time consuming work in background thread. It sounds easy but believe me implementation is pain. If you are using kotlin you can use doAsync or Coroutine but if you are using RxJava you can achieve this without much changes in your code.
 
I have a use case where I have to download the given files in background using WorkManager. Well, here comes the pain, "We have to download all the images and then return success or failure or retry Result to the work manager". How do we hold the thread until Download is complete? 
Initially I have solved this with the CountDownLatch, I implemented and got a working code with that. But it was messy code.

If you are using RxJava, We can do this with operator "blockingGet()" for this your Observable should be "Single". 

https://gist.github.com/BalakrishnanPT/ea6281f15f5dc7882c2e74b3ec46b848

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️