Retrofit and RxJava android example
In this tutorial, well be implementing Retrofit calls using RxJava in android app. Well be creating an application that populates a RecyclerView using Retrofit and RxJava. Well be using a CryptoCurrency API. Show What Will You Learn?
Well be using Java 8 in our Android Application to unleash lambda expressions. OverviewRetrofit is a REST client that uses OkHttp as the HttpClient and JSON Parsers to parse the response. HttpLoggingInterceptor is used to log the data during the network call. RxJava is a library that is used for asynchronous and reactive programming in the form of streams. To use RxJava in retrofit environment we need to do just two major changes:
To do multiple calls or transform the response, we use RxJava operators. Project StructureAdd the following dependencies in our build.gradle file: implementation 'com.android.support:cardview-v7:27.1.0' implementation 'com.android.support:design:27.1.0' implementation('com.squareup.retrofit2:retrofit:2.3.0') { exclude module: 'okhttp' } implementation 'com.squareup.retrofit2:converter-gson:2.3.0' implementation 'io.reactivex.rxjava2:rxjava:2.1.9' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' implementation 'io.reactivex.rxjava2:rxandroid:2.0.1' implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'CodeThe code for the layout activity_main.xml is given below. The code for the CryptocurrencyService.java class is given below. package com.journaldev.rxjavaretrofit; import com.journaldev.rxjavaretrofit.pojo.Crypto; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Path; public interface CryptocurrencyService { String BASE_URL = "https://api.cryptonator.com/api/full/"; @GET("{coin}-usd") Observable@Path passes in the path we specify into the curly braces. The POJO class Crypto.java is given below: package com.journaldev.rxjavaretrofit.pojo; import com.google.gson.annotations.SerializedName; import java.util.List; public class Crypto { @SerializedName("ticker") public Ticker ticker; @SerializedName("timestamp") public Integer timestamp; @SerializedName("success") public Boolean success; @SerializedName("error") public String error; public class Market { @SerializedName("market") public String market; @SerializedName("price") public String price; @SerializedName("volume") public Float volume; public String coinName; } public class Ticker { @SerializedName("base") public String base; @SerializedName("target") public String target; @SerializedName("price") public String price; @SerializedName("volume") public String volume; @SerializedName("change") public String change; @SerializedName("markets") public ListcoinName is a field weve set. Using the magic of RxJava well set a value on this field to transform the response. Creating a Single Call Using RxJavaCryptocurrencyService cryptocurrencyService = retrofit.create(CryptocurrencyService.class); ObservablesubscribeOn() creates a Scheduler thread over which we do the network call.
subscribeOn() vs observeOn()
AndroidSchedulers.mainThread() is a part of RxAndroid and is used to observe the data on the main thread only. subscribe method is what triggers the retrofit call and gets the data in the method handleResults which well see shortly. Multiple CallsWe use the RxJava operator merge to do two retrofit calls one after the other. Observable
Transforming the ResponseTo transform the POJO response we can do the following: Observable
We use Observable.fromIterable to convert the the map result into Observable streams. MainActivity.javaThe code for the MainActivity.java class is given below:
handleResults and handleError are invoked using the Java 8 invocation :: The code for the recyclerview_item_layout layout is given below. The code for the RecyclerViewAdapter.java class is given below: package com.journaldev.rxjavaretrofit; import android.graphics.Color; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.journaldev.rxjavaretrofit.pojo.Crypto; import java.util.ArrayList; import java.util.List; public class RecyclerViewAdapter extends RecyclerView.AdapterThe output of the above application in action is given below: The above output merges the results of the Bitcoin and Ethereum market prices done through retrofit. This brings an end to this tutorial. You can download the Android RxJavaRetrofit Project from the link below. RxJavaRetrofit
|