GENERIC-10: Avoid nested callbacks, as they could lead to a “callback hell”. Approximatively, more than 2 levels of callbacks are considered to reduce maintainability and understandability. This problem is commonly fixed by taking advantage of the RxJava library.


Description

Using too many callbacks leads to unreadable code. These callback hells often arise when multiple server requests need to be performed for one activity. For example, showing the details of users. First you need to know which users exist, and with each username you can request the details. The RxJava library can simplify our code.

Example

For this example we will look at the MVVM example to retrieve my github contributors. We use for this example Rxjava in combination with retrofit. Sometimes it is necessary to have nested callbacks. Like in this example, where we want to find the contributors of our repository. We need to know which repositories there are before we can look up, the contributors of the repository.

Our methods getRepositories() and getContributors(String repo), both return observable Values. Which means that this values can be viewed by an Observer, which we need to Implement.

We then create a Retrofit class, which returns a Retrofit instance, which will perform our API requests to “https://api.github.com/”

In our repository, we will return our A Single object. Which either emits one value, or an error message.

The getContributorList() performs for each Repository in my github account a new request. These repositories are retrieved via the myAPI.getRepositories() request. Then .flatMapIterable(x -> x) flattens a stream of iterables. So that for each repository, we can fetch the contributors, and sort them based on the amount of contributions.

If we had to write this code without RxJava, we would end up with a for loop within two nested callbacks. Which would lead to ugly code.

Checkout the RXJava documentation to understand more about Observers and Observables

Whenever using RXJava or Retrofit do not forget to add these libraries to your app/build.gradle file.

Checkout our MVVM example to view the complete repository.