Monday, June 26, 2023

How to use RxJava to process multiple threads in parallel & in sequence

 Hi,

In this blog I will discuss 2 scenarios where RxJava threading can be helpful:

1. Run Multiple threads in parallel & wait for all of them to complete

2. Run threads sequentially (one after another)


First, add the below dependency in Maven

<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjava</artifactId>
<version>2.2.21</version>
</dependency>
Below are the 2 Completable threads created
import io.reactivex.Completable;
import io.reactivex.schedulers.Schedulers;
Completable cp1= Completable.fromAction(()->{
//business logic
}).subscribeOn(Schedulers.io());

Completable cp2= Completable.fromAction(()->{
//business logic
}).subscribeOn(Schedulers.io());
Now for scenario 1
cp1.mergeWith(cp2).blockingAwait(); // cp1 & cp2 will run concurrently & wait for complete for both tasks

For scenario 2

No comments:

Map to List Using Guava

Suppose, we have a list of Employee objects where we want to create a Map from the list with employee id as Key. You can do that with Java S...