In this tutorial, we’ll be implementing RxJava with Retrofit such that the Retrofit Service is called every x seconds in our Android Application.

Android RxJava and Retrofit

We have already discussed the basics of RxJava and Retrofit together, here.

In order to create a Retrofit service that runs after certain time intervals, we can use the following :

Handlers are used to communicate/pass data from the background thread to the UI thread

Using RxJava we can do much more than that and very easily as well, using RxJava operators.
We can use the interval operator to call a certain method ( retrofit network call in our case) after every given period.

Observable.interval operator is used to emit values after certain intervals. It looks like this:

1000 is the initial delay before the emission starts and repeats every 5 seconds.

We can subscribe our observers which would call the Retrofit method after every 5 seconds.

Calling Retrofit service after certain intervals is fairly common in applications that provide live updates, such as Cricket Score application etc.

Let’s get started with our implementation in the following section. We’ll be creating an application which shows a new random joke in the TextView after every 5 seconds.

Project Structure

android-retrofit-rxjava-timer-interval-project-structure (1)

Add the following dependencies to the build.gradle file:

In order to use lambda syntax, make sure that the compile options are set as the following inside the android block in the build.gradle.

Code

The code for the activity_main.xml layout is given below:

We’ll be using the following public API:
https://api.chucknorris.io/jokes/random.

Create an APIService.java class where the API is defined:

Following is the POJO model for the Jokes.java class :

The code for the MainActivity.java is given below:

setLenient() is used to prevent Misinformed JSON response exceptions.

The disposable instance is unsubscribed when the user leaves the activity.

Check the isDisposed method on the Disposable before creating the Observable stream again in the onResume method.

The output of the application in action is given below:

android retrofit rxjava call every x seconds output

That brings an end to this tutorial. You can download the project from the link below:

By admin

Leave a Reply