Book Image

Learning RxJava

By : Thomas Nield
Book Image

Learning RxJava

By: Thomas Nield

Overview of this book

RxJava is a library for composing asynchronous and event-based programs using Observable sequences for the JVM, allowing developers to build robust applications in less time. Learning RxJava addresses all the fundamentals of reactive programming to help readers write reactive code, as well as teach them an effective approach to designing and implementing reactive libraries and applications. Starting with a brief introduction to reactive programming concepts, there is an overview of Observables and Observers, the core components of RxJava, and how to combine different streams of data and events together. You will also learn simpler ways to achieve concurrency and remain highly performant, with no need for synchronization. Later on, we will leverage backpressure and other strategies to cope with rapidly-producing sources to prevent bottlenecks in your application. After covering custom operators, testing, and debugging, the book dives into hands-on examples using RxJava on Android as well as Kotlin.
Table of Contents (21 chapters)
Title Page
Credits
About the Author
Acknowledgements
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Switching


In RxJava, there is a powerful operator called switchMap(). Its usage feels like flatMap(), but it has one important behavioral difference: it will emit from the latest Observable derived from the latest emission and dispose of any previous Observables that were processing. In other words, it allows you to cancel an emitting Observable and switch to a new one, preventing stale or redundant processing.

Say we have a process that emits nine strings, and it delays each string emission randomly from 0 to 2000 milliseconds. This is to emulate an intense calculation done to each one, as demonstrated here:

import io.reactivex.Observable;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
public class Launcher {
    public static void main(String[] args) {
       Observable<String> items = Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon",
                        "Zeta", "Eta", "Theta", "Iota");
       //delay each String to emulate an...