A brief memo on data sources in RxJava2. Few, clearly, only important.

Observable

Standard data source. Doesn’t support backpressure.

Observable.range(1, 3).subscribe(
        { data -> Log.d("RXJAVALOG", "Observable onNext: $data") },
        { error -> Log.d("RXJAVALOG", "Observable onError: ${error.message}") },
        { Log.d("RXJAVALOG", "Observable completed") },
        { disposable -> Log.d("RXJAVALOG", "Observable onSubscribe: ${disposable.isDisposed}") }
)

If you wish, you can unsubscribe by disposable.dispose()

Flowable

The same, but with backpressure support:

Flowable.range(1, 3).subscribe(
        { data -> Log.d("RXJAVALOG", "Flowable onNext: $data") },
        { error -> Log.d("RXJAVALOG", "Flowable onError: ${error.message}") },
        { Log.d("RXJAVALOG", "Flowable completed") },
        { subscription -> subscription.request(Long.MAX_VALUE) }
)

Single

Gets a single data block, without any onNext:

Single.just("single data").subscribe(
        { data -> Log.d("RXJAVALOG", "Single onSuccess: $data") },
        { error -> Log.d("RXJAVALOG", "Single onError: ${error.message}") }
)

Completable

Starts something on execution and waits for the result. Updating data on the server, writing to the database, etc…

Completable.timer(1, TimeUnit.SECONDS).subscribe(
        { Log.d("RXJAVALOG", "Completable completed") },
        { error -> Log.d("RXJAVALOG", "Completable onError: ${error.message}") }
)

Maybe

Mix of Single and Completable. If something returned – excellent, it is given in onSuccess. Nothing returned – just execute the code in onComplete:

// With data
Maybe.just("single data").subscribe(
        { data -> Log.d("RXJAVALOG", "Maybe 1 onSuccess: $data") },
        { error -> Log.d("RXJAVALOG", "Maybe 1 onError: ${error.message}") },
        { Log.d("RXJAVALOG", "Maybe 1 completed") }
)

// Without data
Maybe.empty<String>().subscribe(
        { data -> Log.d("RXJAVALOG", "Maybe 2 onSuccess: $data") },
        { error -> Log.d("RXJAVALOG", "Maybe 2 onError: ${error.message}") },
        { Log.d("RXJAVALOG", "Maybe 2 completed") }
)

Leave a Reply