DEV Community

BalaKrishnan
BalaKrishnan

Posted on

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)