In this chapter, you won’t be writing any code. Instead, you’ll learn the theory behind one of the most popular open source libraries for Java: RxJava.

You may be wondering: Why learn about RxJava if this is a book written in Kotlin?

Even though RxJava is a Java library, it’ll work with your Kotlin code. This is because Kotlin was designed with Java interoperability built in.

You might also be wondering: I thought this was a book about architecture patterns!

True, this is a book about architecture patterns for Android, but RxJava makes use of important elements that are present amongst most of the architecture patterns you’ll see in this book, such as Observables and Reactive Programming. Also, RxJava is popular, and a lot of source code that you’ll encounter online use RxJava. So, it’s important that you understand how this library works, at least at a high level.

What is the Observer pattern?

Before you dive into the RxJava world, it’s critical that you understand the Observer pattern. When most Android developers hear the word pattern, they immediately think about MVC, MVP and MVVM. In reality, those are not technically patterns; they’re compound patterns.

What is a compound pattern?

A compound pattern is a pattern made up of multiple patterns. In other words, a pattern of patterns.

How does the Observer pattern work?

The Observer pattern helps your objects know when something happens — such as a database update or a network response — so they can react accordingly.

Getting to know RxJava

RxJava is an open-source library for Java and Android that helps you create reactive code. It offers the possibility to implement the Observer pattern for Observable/Observer callbacks and gives you a range of operators that allow you to handle asynchronous and event-based programs.

Programming reactively

RxJava helps you create reactive code. In imperative programming, you often evaluate an expression linearly or line-by-line. If you want to calculate the area of a rectangle, your code would look like this:

var width = 2
var height = 3
var area = width * height // z is 6
button.setOnClickListener {
  //Some code
}

Observing events

RxJava implements the Observer pattern via two main interfaces: Observable and Observer. One of the most important methods in the Observable interface is subscribe().

Creating an Observable

There are many libraries in Java that help you create an Observable from almost any type of event. But sometimes it’s better to create your own. You can create an Observable using Observable.create(). Here’s its signature:

Observable<T> create(ObservableOnSubscribe<T> source)
public interface ObservableOnSubscribe<T> {
  void subscribe(ObservableEmitter<T> e) throws Exception;
}
public interface Emitter<T> {
  void onNext(T value);
  void onError(Throwable error);
  void onComplete();
}
//1
fun createYoutuber(): Observable<String>{
  //2  
  return Observable.create{emitter ->
    //3                       
    emitter.onNext("How to breed llamas")
  }
}
//1
private fun createSubscriber(): Observer<String> {
  //2
  return object : Observer<String> {
    //3
    override fun onSubscribe(d: Disposable) {
      Log.d(TAG, " Im subscribed")
    }
     //4
    override fun onNext(value: String) {
      Log.d(TAG, "New Video : $value")
    }
    //5
    override fun onError(e: Throwable) {
      //Define onError() Action
    }
    //6
    override fun onComplete() {
      //Define onComplete() Action
    }
  }
}
createYoutuber().subscribe(createSubscriber())
D/MainActivity: Im subscribed
D/MainActivity: New Video : How to breed llamas
fun createYoutuber(): Observable<String>{
  return Observable.just("How to breed Llamas")
}
D/MainActivity: Im subscribed
D/MainActivity: New Video : How to breed llamas

Asynchronous tasks

One common misconception about RxJava is that the tasks executed with this library are executed on a background thread. By default, RxJava does all of the tasks in the same thread from which it was called. For an Android app, this means that an Observable will usually emit all its data using the UI thread unless told otherwise.

createYoutuber()
    // Subscribe on a background thread
    .subscribeOn(Schedulers.io())
    // Observe on the main thread
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(createSubscriber())
D/MainActivity: Im subscribed
D/MainActivity: New Video : How to breed llamas

Operators

YouTube is great, but there are other video streaming services available. Perhaps you’d like to subscribe to more than just a YouTube Observable, but apply the same logic to each.

fun createNetflixChannel(): Observable<String> {
  return Observable.just("House of Cards")
}
val subscriber = createSubscriber()
createYoutuber()
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(subscriber)

createNetflixChannel()
   .subscribeOn(Schedulers.io())
   .observeOn(AndroidSchedulers.mainThread())
   .subscribe(subscriber)
Observable.merge(createYoutuber(), createNetflixChannel())
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(createSubscriber())
D/MainActivity:  Im subscribed
D/MainActivity:  Im subscribed
D/MainActivity: New Video : How to breed Llamas
D/MainActivity: New Video : House of Cards

Frequently Not Asked RxJava Questions

Q. Can I use the usual listeners/callbacks instead of RxJava?

Key points

  • The Observer pattern helps your objects know when something interesting happens so they can react accordingly.
  • The Observer pattern defines a one to many relationship between an Observable and the Observers.
  • An Observable is an object that emits notifications about its state to one or more Observers.
  • Reactive Programming is a declarative programming paradigm in which you dynamically react to changes.
  • RxJava is an open source library for Java and Android that helps you create reactive code. It’s heavily inspired by functional programming.
  • RxJava implements the Observer pattern with two main interfaces: Observable and Observer.
  • RxJava executes all tasks on the same thread from which it was called.

Where to go from here?

RxJava is a powerful and popular library that lets you write reactive code in your Android Projects. Even though it was written in Java, it’s 100% interoperable with Kotlin. If you want to learn more about RxJava, check out Irina Galata’s on the site Reactive Programming with RxAndroid in Kotlin raywenderlich.com/384-reactive-programming-with-rxandroid-in-kotlin-an-introduction

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.