Chapter 2. Networking with observables

 

In this chapter

  • Implementing the network layer with RxJava
  • Taking a deeper look at the RxJava library
  • Working with observables and subscribers
  • Basic error handling
  • Introducing immutability

RxJava and event streams

In the preceding chapter, you briefly saw how to use RxJava and the RxBindings utility to handle events originating in the UI—namely, the text the user has entered in an EditText.

In that case, your flow was simple: you’ll have some events that come, you’ll apply a bit of processing, and then you’ll show results.

In this chapter, you’ll look at an example that is commonplace: network requests.

RxJava and networking

In the beginning, RxJava looks like a more convenient way of declaring callbacks, but later in the chapter you’ll see a couple of cases that can get smelly fast with the traditional ways of implementation.

RxJava is indeed often adopted as a way to alleviate the “callback hell” that results when you need to combine data from multiple APIs. You’ll see how this can be elegantly handled with observables.

Libraries for network requests on Android

In this book, you’ll use a library called Retrofit from Square for networking purposes. It’s a reasonably standard one, and has a powerful syntax for declaring interfaces. It’s also able to play well with RxJava, which you’ll use to your benefit.

You can add the dependence in your Gradle file like this (check the latest version on http://square.github.io/retrofit/):

Subscribers

RxJava 2 observable types

Subscribing to and converting different observables

What happens when you make a normal network request?

What happens when you make a network request with an observable?

Network request as an observable

Example: An RSS feed aggregator

The feed structure

Getting the data

The combineLatest operator

The Rx code so far

Coffee break

Asynchronous data processing chains

sitemap