RxJava

RxJava is a library for writing event-based, asynchronous code using observable streams. RxJava provides a lot of functionality and is quite powerful. However, it can also be used for simple asynchronous code as well.

A simple example of using RxJava to run some work on a background thread can be seen in the following code snippet:

Single.fromCallable {
Thread.sleep(5000)
"Single is done"
}
.observeOn(Schedulers.io())
.subscribe { value -> println(value) }

With RxJava, we can define how our events will be emitted, which schedules should be used to run the work, and then manage the completion of that work. This is quite similar to the CompletableFuture API we looked at previously.

With RxJava, we can also perform more advanced operations such as transforming our streams of data:

Single.fromCallable {
Thread.sleep(5000)
"Single is done"
}
.map { RequestResult(it) }
.observeOn(Schedulers.io())
.subscribe { value -> println(value) }

In this example, we've applied the map() method to transform the emitted String value into an instance of a RequestResult class. This type of transformation of asynchronous streams of data is one reason why RxJava is such a popular library.

It should be noted that while RxJava can be used for writing simple asynchronous code that isn't necessarily event-driven, it might be overkill for such a use case. RxJava is a large dependency that provides many different operators to address a number of use cases. For simpler cases, something like CompletableFuture or coroutines might be a more lightweight solution.