Redeem Now
Read More
Read now

How to Handle Api Call Using Rxjava2 and Retrofit2 in android


In this blog we are going handle api calls using Rxjava and Retrofit library which makes simple and cleaner way to define API.

RxJava is a Java VM implementation of Reactive Extensions a library for composing asynchronous and event-based programs by using observable sequences.

Retrofit is a REST Client for Android and Java. It makes it relatively easy to retrieve and upload JSON. Retrofit uses the OkHttp library for HTTP requests.

Add the following dependencies to your gradle file

Once the dependencies are all set up, We would need an instance of Retrofit to make network calls.

baseUrl-> Set up Base URL of API

addConverterFactory() — converter factory for serialization and deserialization of objects

We can define post parameter for the API. The APIs are declared in an interface:

In Rx, the subscriber implements three methods to interact with observable:

  1. onNext(Data): Receives the data from the observable
  2. onError(Exception): Gets called if an exception is thrown
  3. onCompleted(): Gets called when the data stream ends

For Android, to subscribe to an observable, we first tell the observable about the threads on which we plan to subscribe to and observe.

Making an API call:

That’s it, we can use the Observable/Flowable returned by the API and subscribe() to it to handle the data

Merging the multiple requests in Rxandroid 

Merge operator combine multiple observable into one


. . .

Comment (1)

Add Your Comment

    Worked! Thanks for code.
  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again