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
cp1.andThen(cp2).subscribe(); //cp2 will run after cp1

No comments:

Convert Java Project from Log4j 1 to Log4j2

Many times while working on old Java projects we find Log4j 1.x is used. But as the Log4j2 is the new one; hence to upgrade to Log4j2 we nee...