dagger with retrofit example part 3
| | |

Dagger With Retrofit And RxJava Example | RecyclerView

This is the third part of Dagger with Retrofit tutorial. In this part, we’re going to make our network request with RxJava and simply show data in RecyclerView.

Note: I strongly recommend you to see my previous blogs this series. If you haven’t seen my previous blogs, then I’m afraid you will not understand.

So, without further ado let’s dive into coding.

Below are the libraries we need to add to our build. Gradle file to make a network request with RxJava and also to work with the retrofit.

// Rx java dependency
implementation 'io.reactivex.rxjava2:rxjava:2.1.8' // please add current version of dependencies.

// Rx Android dependency
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1' 

// Rx java adapter version
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

Now we need little more improvement in ServiceUtilModule to tell the retrofit builder that we want you to enable RxJava in a network request. By the way, ServiceUtilModule is a part of the dagger which I discussed in the first tutorial.

Below is the code for creating retrofit with RxJava Adapter which is in ServiceUtilModule.

@Provides
@CustomApplicationScope
Retrofit getRetrofit(OkHttpClient okHttpClient, Gson gson) {
    return new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // RxJava Adapter Factory instance for network request.
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .build();
}

Here we need to update our ServiceUtil interface. We have to change the return type of our Network Method from Call to Observable.

ServiceUtil

public interface ServiceUtil {

    @GET("GetCarsCategories.php")
    Observable<CarCategoryResponse> getCarCategories();
}

So, you guys holding just want to make sure because interesting part comes in where we are actually going to see the magic of RxJava. In here we need to update our MainActivity code. In MainActivity we are only updating retrofit network request code, remaining code will be pretty much same.

Below is network call with RxJava, and I believe you guys know lambda’s as well.

disposable = serviceUtil.getCarCategories()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(carCategoryResponse -> {
                    if (carCategoryResponse.getCarCategories() != null && carCategoryResponse.getCarCategories().size() > 0) {
                        this.carCategories.addAll(carCategoryResponse.getCarCategories());
                        carCategoryAdapter.notifyDataSetChanged();
                    } else
                        Toast.makeText(this, "No data found!", Toast.LENGTH_SHORT).show();
                }, throwable -> {
                    if (mainProgressBar.getVisibility() == View.VISIBLE)
                        mainProgressBar.setVisibility(View.GONE);
                    Toast.makeText(this, "Internet not connect", Toast.LENGTH_SHORT).show();
                }, () -> {
                    if (mainProgressBar.getVisibility() == View.VISIBLE)
                        mainProgressBar.setVisibility(View.GONE);
                });

I believe many of you really don’t understand what is just happened. So, don’t worry I’m going to explain this line by line, because this is our main topic RxJava right. So, let’s do it.

Below is the first line of calling getCarCategories function.

serviceUtil.getCarCategories()

In here we actually making our network request with RxJava and getting observable as return type nothing fancy.

The following shows the second line of code.

.subscribeOn(Schedulers.io())

The subscribeOn function basically asking in which thread you want to run your network request. So, we are telling that we want to run our network request in a background thread bypassing Schedulers.io. If we do not execute network request in background thread then our app crashes and we get an error by saying NetworkOnMainThreadException.

The following shows the third line of code.

.observeOn(AndroidSchedulers.mainThread())

The observeOn function asking in which thread you want your response back. So, we’re telling that we want our response back in main thread by passing AndroidSchedulers.mainThread. If we do not listen in the main thread then our app crashes and we get an error by saying CalledFromWrongThreadException.

Below is the fourth line code. The first parameter of subscribes function.

subscribe(carCategoryResponse -> {
                    if (carCategoryResponse.getCarCategories() != null && carCategoryResponse.getCarCategories().size() > 0) {
                        this.carCategories.addAll(carCategoryResponse.getCarCategories());
                        carCategoryAdapter.notifyDataSetChanged();
                    } else
                        Toast.makeText(this, "No data found!", Toast.LENGTH_SHORT).show();
                }

The subscribe method in which we are actually getting our response back. Subscribe function accepting Consumer Interface as a parameter. The consumer interface accepting CarCategoryResponse object and with that, we’re performing some basics stuff like setting RecyclerView data.

The second parameter of subscribes function.

throwable -> {
                    if (mainProgressBar.getVisibility() == View.VISIBLE)
                        mainProgressBar.setVisibility(View.GONE);
                    Toast.makeText(this, "Internet not connect", Toast.LENGTH_SHORT).show();
                }

The second parameter of subscribes method accepting consumer interface but here consumer Interface accepting a Throwable. If any error occurred during the network request this interface will be hit. So, that’s why we’re setting visibility gone to our ProgressBar and show some Toast.

The third parameter of subscribes function.

() -> {
                   if (mainProgressBar.getVisibility() == View.VISIBLE)
                       mainProgressBar.setVisibility(View.GONE);
               }

The third parameter of subscribes method accepting Action interface. This will be called if everything goes right. So, in here we just need to hide the ProgressBar.

Note: Action interface will not be called if the error occurred during the network request. It will only call Consumer with accepting Throwable object interface.

Now one last thing remains which is DisposableThe subscribes method return type is Disposable. We can use disposable to dispose of the running task in onStop.

@Override
protected void onStop(){
    if(disposable != null && !disposable.isDisposed())
        disposable.dispose();
}

This is how we can stop our currently running tasks with disposable in RxJava.

So, this is it our example with Dagger and RxJava is complete. I hope you guys have a good understanding of how to make a network request with RxJava

Download Complete Code

If you’ve any queries regarding this post, please do comment below.

Thank you for being here and keep reading…

Previous Part

Similar Posts

3 Comments

  1. I absolutely love your website.. Pleasant colors & theme.
    Did you build this site yourself? Please reply back as I’m hoping to create my
    very own blog and would love to find out where you got this from or exactly what the theme is called.
    Thank you!

Comments are closed.