Retrofit and RxJava

Retrofit and RxJava

What is Retrofit?

Simply if you need to send or receive data from server you need to serialize data to be able to retrieve it.

To make this point clear assume that we need to send user registration data to our server

This is the data which user entered:

username: Eslam, password: 1234, address: Cairo.

We can send it as following (Eslam,1234,cairo), here is the question which one of this data is the user name, me and you know where is user name , but we still need to make server and mobile know!, what about sending data with the following pattern

{"user_name":"Eslam", "Password":"1234", "Address":"Cairo"} (This pattern called Json)

We now sure the data can be retrieved .

Okay, Now we need to send this data to the server let's think about what we need

  1. Create Json from Model (POJO) "Simple Class can hold this data"
  2. Create thread which will used to connect with server
  3. Create HTTP request that will deal with server to send data
  4. Handle HTTP responses and resend data if there are something wrong

Each point of previous has along details and hours of coding.

So Square team Create Library named Retrofit ,

This library will handle all of this points, it will take POJO from you and send it to server with several lines of code, it will create thread and handle requests and responses and Json and more operations.

Also Retrofit can work on top of several libraries like gson, jackson, wire, okhttp and rxjava

How we download Retrofit?

by using gradle you can type the following:

To download retrofit

compile 'com.squareup.retrofit2:retrofit:2.3.0'

To download Gson (To parse json format)

compile 'com.google.code.gson:gson:2.6.1'

To make integration between gson and retrofit

compile 'com.squareup.retrofit2:converter-gson:latest.version'

To download rxjava

compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.7'

To integrate between rxjava and retrofit

compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

By adding the previous you will be able to use retrofit and gson and rxjava all together.

How To Start?!

After adding dependencies from previous section you now can be able to start using retrofit and rxjava

1- You need to create POJO's (you can create it from json from this website )

it will be something like this

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class User{
    @SerializedName("user_name")
    @Exposeprivate String userName;
    @SerializedName("password")
    @Exposeprivate String password;
    @SerializedName("address")
    @Exposeprivate String address;



    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password= password;
    }
    public String getAddress() {
        return address;
    }

    public void setUserName(String address) {
        this.address = address;
    }

}

2- You need to create interface that will handle your requests, it will be like this.

public interface API{

    @GET("/users/{user}")
    Call<User> getUser(@Path("user") String user);
    @GET("/users")
    Call<List<User>> getUsers();


    @GET("/users/{user}")
    Observable<User> getUserObservable(@Path("user") String user);
    @GET("/users")
    Observable<List<User>> getUsersObservable();

}

3- You need to create Instance from retrofit that will manage everything

Retrofit retrofitInstance = new Retrofit.Builder()
                                .baseUrl("YOUR_BASE_URL")
                                .addConverterFactory(GsonConverterFactory.create())
                                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                                .build();

lets describe the previous code

you need to create new instance from Retrofit, so you typed

new Retrofit.Builder()

then you need to give it the base url of your server, so you typed

.baseUrl("YOUR_BASE_URL")

then you need to tell it you must use Gson library, so you typed

.addConverterFactory(GsonConverterFactory.create())

then you need to tell it you need to work with rxjava2 when i deal with Observers, so you typed

.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

Finally you need to get Retrofit instance with the previous settings, so you typed

.build();

Now you are ready to get your data

To get Data by using retrofit callbacks

//link between API interface and retrofit instance
API usersApi = retrofitInstance.create(API.class);

//send get user method and enquee your request to execute
usersApi.getUser("eslam").enqueue(new Callback<User>() {
    @Overridepublic void onResponse(Call<User> call, Response<User> response) {
        //This method will executed when response is ready //also you can check if response is sussessed or not by the followingif(response.isSuccessful()){
            User x = response.body();
        }
    }

    @Overridepublic void onFailure(Call<User> call, Throwable t) {

    }
});

Or you can get data using rxjava2

//link between API interface and retrofit instance
API usersApi = retrofitInstance.create(API.class);

usersApi.getUserObservable("eslam").subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ServerResponse>() {
    @Overridepublic void onSubscribe(Disposable d) {

    }

    @Overridepublic void onNext(User user) {
        //User named user :)
    }

    @Overridepublic void onError(Throwable e) {

    }

    @Overridepublic void onComplete() {

    }
});

Thanks.

Good article. there's a point I can't I understand why do we need to use Rxjava Retrofit work on background thread,isn't it? can we instead of Rxjava using asyncTask? why Rxjava be better than asyncTask?  Thanks in advance.

Like
Reply

good one how can do this with images

Like
Reply

Good post, short and easy to understand ;)

To view or add a comment, sign in

More articles by Eslam Ahmad

  • Kotlin Android / KMP Benchmarking

    We all love the social media videos, specially the short videos (it's funny), we may have some work and deliverables to…

  • How KMM can enhance business analytics numbers

    Please Feel free to add a comment to correct me, recommend an edit, and if you do like it, clap and share 🫶😅…

  • Unit Tests - Basics - Part 1

    In this series of articles i need to take chance to share my knowledge in unit testing with you, also it will great if…

    11 Comments
  • Koin - Light, simple Kotlin DI Framework

    As i mentioned in previous article, i will write articles to try to illustrate how to use koin in your code, to avoid…

    1 Comment
  • Stop using dagger

    Dagger is a dependency injection library, used to create testable code. But you payoff time and headache to make your…

    2 Comments
  • How to use Rxjava with Dagger2 and Retrofit and OkHttp and Gson

    In this article we will see how to create a complete project using rxjava, dagger2, retrofit, okhttp and Gson Click…

    2 Comments

Others also viewed

Explore content categories