Reactive Programming: Android Networking

by Dr. Yan
  java, android, reactive

Reactive programming allows you to compose asynchronous actions in some pretty cool ways. A great way to show this is using network calls; RxJava will handle all of the threading and error handling for you. Using Square’s Retrofit library and RxJava, a simple HTTP request would look like this:

apiClient.getUser(token)
    .subscribeOn(Schedulers.io()) // Thread of the network call
    .observeOn(AndroidSchedulers.mainThread()) // Thread of the subscribe block
    .subscribe({ user -> 
        // Do something with User
    },
    {error -> 
        // Woops
    })

The error block here will handle any non 200 response from the HTTP request.

We can compose multiple network calls together using different Rx operators. One such operator is flatMap. Here is a chained network call fetching a user token and then using that token to fetch a user profile:

apiClient.login(username, password)
    .flatMap { response ->
        apiClient.getUser(response.token)
    }
    .subscribeOn(Schedulers.io()) // Thread of the network call
    .observeOn(AndroidSchedulers.mainThread()) // Thread of the subscribe block
    .subscribe({ user -> 
        // Do something with User
    },
    {error -> 
        // Woops
    })

Any error in either network call will fall into the final error block.

Now we can put it all together with the view binding code:

RxView.clicks(loginButton)
    .throttleLast(2, TimeUnit.SECONDS)
    .flatMap {
        apiClient.login(username.text, password.text)
    }
    .flatMap { response ->
        apiClient.getUser(response.token)
    }
    .subscribeOn(Schedulers.io()) // Thread of the network call
    .observeOn(AndroidSchedulers.mainThread()) // Thread of the subscribe block
    .subscribe({ user -> 
        // Do something with User
    },
    {error -> 
        // Woops
    })