Reactive Programming with RxJava

- 3 mins

ReactiveX

Reactive Extensions (ReactiveX)


Update note: I wrote this series for RxJava 2.x in 2019. RxJava 3.x changed some APIs. See the RxJava 3.x migration guide when using that version.

I enjoyed Thomas Nield’s Learning RxJava. These are my notes on RxJava 2.

Why RxJava?

Quickstart

In RxJava 2, an Observable<T> emits values of type T to a subscriber. Operators can transform those values before the subscriber receives them.

This Observable<String> contains three strings:

fun main() {
    val observable = Observable.just("Hello", "world", "!")
}

This method creates an observable but does not subscribe. Add a subscriber to print its values:

fun main() {
    val observable = Observable.just("Hello", "world", "!")
    observable.subscribe {
        print("$it ")
    }
}

This time, the output is the following:

Hello world !␠

The subscriber prints each string followed by a space. In the output above, ␠ marks the final space.

Use map() to transform each string before printing it:

fun main() {
    val observable = Observable.just("Hello", "world", "!")
    observable.map { it.uppercase() }.subscribe { print("$it ") }
}

The output uses the same spacing:

HELLO WORLD !␠

RxJava vs Java 8 streams

An Observable emits items to subscribers. Java streams and Kotlin sequences yield items when consumers request them. RxJava also supplies operators for asynchronous events and scheduler control.

RxJava Series Guide

This is a comprehensive guide to RxJava organized by topic. Follow the links below for in-depth coverage:

Fundamentals

Operators

Advanced Topics

Flow Control

Backpressure

Customization

Sources

These Kotlin examples use RxJava directly. RxKotlin offers Kotlin-specific extensions.

Mouaad Aallam

Mouaad Aallam

Software Engineer

rss facebook twitter x bsky github youtube mail spotify instagram linkedin google pinterest medium vimeo mastodon gitlab docker