RxJava - Coding Infinite https://codinginfinite.com/rxjava/ Your infinite Coding Solutions Fri, 11 Oct 2019 08:00:59 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 https://codinginfinite.com/wp-content/uploads/2018/07/CODING-INFINITE-FAVICON.png RxJava - Coding Infinite https://codinginfinite.com/rxjava/ 32 32 Android Room Persistence Example https://codinginfinite.com/android-room-tutorial-persistence/ https://codinginfinite.com/android-room-tutorial-persistence/#comments Fri, 25 May 2018 00:23:27 +0000 http://codinginfinite.com/?p=451 Today we’re gonna look out a new Android Architecture Component library called Room. The room is basically a “Persistence library that provides an abstraction over SQLite“. The room is a new way to create the database in your Android apps. Although the Android framework provides built-in support for SQLite database, there are many drawbacks working with SQLite....

The post Android Room Persistence Example appeared first on Coding Infinite.

]]>
Today we’re gonna look out a new Android Architecture Component library called Room. The room is basically a “Persistence library that provides an abstraction over SQLite“. The room is a new way to create the database in your Android apps. Although the Android framework provides built-in support for SQLite database, there are many drawbacks working with SQLite.

Drawbacks Of SQLite

Before the start, I want to clarify the drawbacks of SQLite database.

  1. You have to write a lot of boilerplate code.
  2. You have to implement object mapping for every query you write.
  3. Difficult to implement database migrations.
  4. Database operation on the main thread.

Components of Room

Now there are three main components for creating the database with the room.

  1. EntityEntity is an annotated class. This annotation is used to create the database table. After adding Entity annotation room will take care of creating the database table for you.
  2. Dao: Dao is also an annotated class. To access the data from the database you used Dao (Data Access Object). In Dao interface, you declare all the methods needed to work with the database.
  3. DatabaseDatabase is an annotated class. In database class, we define all of our Entity class and tell the version of the database.

Android App Coding

So, enough of this theory let’s build a real-life scenario app. We’re going to create a Book Library app. In this app, the user adds a book name and select the who is the author then insert the book along with author name into the database.

Alright first create a new project in Android Studio with empty activity. Now add the Room dependency into a build.gradle file.

// Room database dependencies
implementation 'android.arch.persistence.room:runtime:1.1.0'   // Use current library version
kapt 'android.arch.persistence.room:compiler:$versions.1.1.0'  // If language is kotlin remain same else use annotationProcessor instead of kapt

Note: If you’re using Kotlin language please add kapt annotation plugin at the top of a build.gradle file.

Now let’s create our first component which is EntityIn our example, we need two Entity classes one for Author of a book and one for Book itself. It means we have two tables in our database.

The following shows how to create our first Entity of Author class.

AuthorModel

@Entity(tableName = "authors")
data class AuthorModel(@PrimaryKey(autoGenerate = true)
                       @ColumnInfo(name = "author_id")
                       val authorId: Long = 0,
                       @ColumnInfo(name = "author_name")
                       var authorName: String)

For Entity, we add the annotation to our class and tell the name of a table. Now in every Entity class, one Primary Key is necessary. In order to tell which value is the primary key annotate with @PrimaryKey. The @ColumnName is for describing the name of table values. The @ColumnName is not necessary for every field if the not defined room will use the variable name when creating the table.

Below is another Entity for BookItem class.

BookItem

@Entity(tableName = "books"
        , indices = [(Index(value = ["book_id"], name = "idx_books_book_id"))],
        foreignKeys =
        [(ForeignKey(
                entity = AuthorModel::class
                , childColumns = ["author_id"]
                , onUpdate = ForeignKey.CASCADE
                , onDelete = ForeignKey.CASCADE))]
)
data class BookItem(@PrimaryKey @ColumnInfo(name = "author_id") val authorId: Long, @ColumnInfo(name = "book_id") val bookId: Long, val name: String)

Now, this Entity class is complicated than the previous one. In BookItem we use a Foreign Key relation with the Author class table. You see every book has an author that’s why we need the authorId to specify who is the author of the book.

We create database tables right, how do we access the data. For accessing the data here comes the Dao’s annotation. For creating a Dao you need to create an interface and annotate with Dao and declares all the methods needed to work with the database. There are four annotations when declaring the methods in Dao’s

  1. InsertInsert for inserting the data.
  2. Update:  For updating the data.
  3. Delete: For deleting the data.
  4. QueryThis annotation is for SQL statement and this checked at compile time. If the query has an error it will tell you at compile time instead of when executing the query.

Note: All of these queries is Synchronous meaning that they will be run on the same thread you’re triggering from. If that’s Main Thread your app will crash IllegalStateExceptionSo, the best approach is that you’ve to run these queries from Background Thread and get the result in Main Thread. For this, you can use RxJava and Kotlin Co-routines.

Now let’s see how we can create a basic Dao interface.

@Dao
interface BaseDao<in T> {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(t: T): Long

    @Delete
    fun delete(type : T)

    @Update
    fun update(type : T)

}

See every database table has some base methods like insert, delete, update etc. So, I create a generic Dao interface and we just need to extend this BaseDao interface.

Below is the AuthorDao interface.

AuthorDao

@Dao
interface AuthorDao : BaseDao<AuthorModel> {

    @Query(value = "SELECT * FROM authors")
    fun getAllAuthors(): List<AuthorModel>

    @Query(value = "SELECT * FROM authors WHERE author_id = :authorId")
    fun getAuthorWithId(authorId: Long): AuthorModel?

    @Query(value = "SELECT author_id FROM authors")
    fun getAllIds(): List<Long>
}

You see with Query annotation we’re providing a SQL query and Room will be able to provide the data according to SQL query.

Below is the BookDao interface.

BookDao

@Dao
interface BookDao : BaseDao<BookItem> {

    @Query(value = "SELECT * FROM books")
    fun getAllBooks(): List<BookItem>

    @Query(value = "SELECT * FROM books WHERE author_id = :authorId")
    fun getBooksWithAuthorId(authorId: Long): List<BookItem>
}

The class, that’s put the Entities and Dao’s together is the RoomDatabaseIn the database class, we define all the Entities and the Version of the database.

Below show’s how to create RoomDatabase class.

BookLibraryDatabase

@Database(entities = [AuthorModel::class, BookItem::class], version = 1)
abstract class BookLibraryDatabase : RoomDatabase() {

    abstract fun authorDao(): AuthorDao

    abstract fun bookDao(): BookDao
}

Everything is done for creating a RoomDatabaseIt’s time to see how can we create RoomLibraryDatabase instance and get the Dao’s object.

Below shows how to create RoomLibraryDatabase instance.

val database = Room.databaseBuilder(context, BookLibraryDatabase::class.java, DATABASE_NAME).build()

So, we have a database object. Now It’s time to use all of the database utility methods that we write in Dao class.

// For inserting the author
Observable.just(database.authorDao().insert(AuthorModel(authorName = "Ahsen Saeed")))
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe({// Author inserted},{it.printStacktrace()})

// Author with Id
Observable.just(database.authorDao().getAuthorWithId(id))
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe({System.out.println(it)},{it.printStacktrace()})

// Get all authors
Observable.just(database.authorDao().getAllAuthors())
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe({ // Here you all authors},{it.printStacktrace()})

// Get books of authors with id
Observable.just(database.bookDao().getBooksWithAuthorId(id))
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe({ // Here you have all books with author id},{it.printStacktrace()})

// Delete the book
Observable.just(database.bookDao().delete(book))
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe({ // Book deleted successfully},{it.printStacktrace()})

// Similarly you can perform all the utility the functions

You guys must be remembered that we need to call these methods from Background Thread and get the result on the Main Thread.

So that’s it, I’m going to end this blog here. I hope you guys, have learned something from this post. If you’ve any queries regarding Room persistence, please do comment below.

I have also written some articles on Room Persistence with RxJava2 and Room Persistence with LiveData.

Thank you for being here and keep reading…

The post Android Room Persistence Example appeared first on Coding Infinite.

]]>
https://codinginfinite.com/android-room-tutorial-persistence/feed/ 2
RxJava with Examples | Reactive Programming for Beginners https://codinginfinite.com/rxjava-examples-reactive-programming-beginners/ Mon, 16 Apr 2018 10:39:00 +0000 http://codinginfinite.com/?p=164 Hey, guys today we’re going to learn about RxJava. RxJava stands for a Reactive extension. RxJava is one of the most popular libraries for reactive programming. Reactive programming basically provides a simple way of asynchronous programming. RxJava follows the Observer pattern. People are gonna say’s you like asynchronous is complex, it’s very hard. All this true working...

The post RxJava with Examples | Reactive Programming for Beginners appeared first on Coding Infinite.

]]>
Hey, guys today we’re going to learn about RxJava. RxJava stands for a Reactive extension. RxJava is one of the most popular libraries for reactive programming. Reactive programming basically provides a simple way of asynchronous programming. RxJava follows the Observer pattern.

People are gonna say’s you like asynchronous is complex, it’s very hard. All this true working with asynchronous is difficult but RxJava library gives you a very simple way to convert your task in to asynchronously very easily. You can achieve this thing with simple java but let me tell you this not an easy thing to do.

The first thing you know about RxJava is there are three constructs.

The first construct is Observable.

Observable:  Observable are the sources for data to emit. An observable start providing data once a subscriber or observer start listening. An Observable may emit n number of items. It will terminate with success or with an error. For example an object of User who emits User object with a new username, when the new username is set.

The second construct is Subscriber or Observer.

Subscriber: Subscriber basically listens to those events emitted by observable. An observable may have any number of subscribers.

The third construct is Schedulers.

Schedulers: Another super huge advantage with RxJava is Instance concurrency. The way RxJava does that is with Schedulers. For example, We say hey you have this observable and this observer when you established this connection, basically do it in this particular thread.

Creating Observable

Various types of creating Observable.

Single: You subscribe to a single either you get back value or an error.

*Either succeeds with an item or error.

* No BackPressure support.

* Think “Reactive scalar”.

Completable: It is a set of code you can run then it may complete successfully or fail.

* Completable similar to a method that return type is void.

* Either completes or errors or has no items.

* No BackPressure support.

* Think “Reactive runnable”.

Maybe: This either has an item error or potentially has no items.

* No BackPressure support.

* Think “Reactive optional”.

Flowable: This either emits 0 item or emits n items terminates with success or with an error event.

* Have BackPressure support.

* Can emit any number of items.

Observable: This either emits 0 item or emits n items terminates with success or with an error event.

* No BackPressure Support.

* Can emit any number of items.

Observables emit table.

Emit SourceReactive StreamNo BackPressure
o..n items,complete,errorFlowableObservable
item,complete,errorMaybe
item,errorSingle
complete,errorCompletable

So, enough of this theory, let’s dive into coding and see how we can create observables.

Before start please add RxJava dependency.

For Java

<dependency>
    <groupId>io.reactivex.rxjava2</groupId>
    <artifactId>rxjava</artifactId>
    <version>2.0.4</version>
</dependency>

Dependency on Android.

compile 'io.reactivex.rxjava2:rxjava:2.0.8'

The following shows an example how we can create simple observable.

Observable<String> helloWorldObservable = Observable.just("Hello World");

RxJava provides so many static methods for creating observables. Just is one of the static methods for creating observable. Just is basically saying give me the observable of hello string. You can pass any object in Just method instead of string to create observable. So, this our first construct for creating observable.

The following shows how we can subscribe to observable.

helloWorldObservable.subscribe(new DefaultObserver<String>() {
            @Override
            public void onNext(String s) {
               System.out.println(s);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

When we called subscribe on observable, observable start emitting item. You see subscribe method accepts Observer interface as a parameter. The onNext() method is called when observable emit new item. The onError() method is called when an error is occurred in emitting. The onComplete() method is called when observable finishes its data flow. So, this is our second construct.

The following show previous example with lambdas.

helloWorldObservable.subscribe(s -> System.out.println(s), throwable -> throwable.printStackTrace(), () -> System.out.println("Emittion completes"));

Let’s see another example of creating observable.

String strings[] = new String[]{"Hello", "World"};     // Array of resource
Observable.fromArray(strings).subscribe(s -> System.out.println(s),throwable -> throwable.printStackTrace(),() -> System.out.println("Emittion completed"));

FromArray is another static method for creating observable. The  FromArray method takes the array of objects and returns the array of object of observable. Now every time onNext() method called, it received a single string value from the array.

The following example shows how you can apply logic before actually receiving the stream.

List<Integer> intergerList = Arrays.asList(54,12,10,78,69,33,66,99,84);
Observable.fromIterable(intergerList)
          .filter(i -> i % 2 == 0)
          .sorted()
          .subscribe(i -> System.out.println(i), throwable -> throwable.printStackTrace(), () -> System.out.println("Emittion completes"));

// Output
10
12
54
66
78
84

FromIterable is another static method for creating observable. The FromIterable method takes the list of objects as a parameter and returns the list of object of observable. Another thing of noticeable here is the chaining of observables. You see every operator returns an observable and we can chain them. The filter method takes the Predicate interface and performs the logic on it. The sorted method sorts the result in ascending order. You can also pass the custom Comparator interface for sorting.

The following example shows how you can merge the result of two observable into one. Another cool feature of a startWith method.

static class Person {

        enum SEX {
            MALE, FEMALE, SHE_MALE
        }

        private String name;
        private int age;
        SEX sex;

        Person(String name, int age, SEX sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
}    This Person class we are going to use in our example.

// Create observable code.
Observable<Person> firstObservable = Observable.create(emitter -> emitter.onNext(new Person("Shayan Tahir", 22, Person.SEX.MALE)));
Observable<Person> secondObservable = Observable.create(emitter -> emitter.onNext(new Person("Bilal Ahmed", 25, Person.SEX.MALE)));
secondObservable.mergeWith(firstObservable)
                .startWith(new Person("Jon Doe", 20, Person.SEX.FEMALE))
                .subscribe(person -> System.out.println(person.name)
                        , Throwable::printStackTrace,() -> System.out.println("Emittion complete"));

// Output

// Jon Doe
// Bilal Ahmed
// Shayan Tahir

Create is another static method for creating observable. The Create method accepts ObservableOnSubscribe interface for creating observable. With Create method we have the ability to call onNext multiple times. Now with merge method, we can merge the output of two observable into one. Another interesting method is startWith. The startWith method returns an Observable that emits a specified item before emitting the sources.

RxJava provides several other methods for creating observable.

Observable.fromCallable(): FromCallable essentially modeling some synchronous behavior that returns a single value.

Observable.timer(): This function means to execute this task every x seconds until someone unsubscribes it.

Observable.interval(): Execute this function every x seconds without delay and stops when someone unsubscribes it.

Observable.concat(): Concatenates the elements of each observable provided by the observables as a parameter.

Note: Similar methods exist in all observable types. Examples Flowable, Maybe, Completeable and Single.

Now, you guy’s must be thinking where is the asynchronous code, how we can handle multithreading with this. Let me tell you what we do before these all are the basics of RxJava how to create observables. Now we’re going to see the real power of RxJava.

The following is the example of how we can create a timer task with observable.

Disposable disposable = Observable.timer(5000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .subscribe(aLong -> {
                              doLongRunningTask();
                        }
                        , Throwable::printStackTrace,
                        () -> System.out.println("Observable complete"));

This piece of code runs after every five seconds and do some long running task. SubscribeOn is the method in which we tell do the task to run in a background thread by giving Schedulers object.

The following example shows how we can make a network request with observable.

Observable<User> userObservable = Observable.fromCallable(() -> client.getUser(request.execute()));

This is how you can make a network request with observables. The client is the network interface. But we have a problem here, that network request still going to be done synchronously. So, what do we do to make it asynchronous?

The following example shows how we can make network request asynchronously with observable.

Observable.fromCallable(() -> client.getUser(request.execute()))
                .subscribeOn(Schedulers.io())
                .subscribe(user -> {
                    // performOperationWithUser(user);
                });

So, we apply an operator that changes the thread with background thread when we subscribe to the observable. The subscribeOn is the operator that changes the current thread with a background thread and accepts a Schedulers object as a parameter.

The following example shows how you can make two asynchronous network request with dependency. The second request depends on first request response.

Observable<User> tempObservable = Observable.fromCallable(() -> client.getUser(request.execute()))
        .subscribeOn(Schedulers.io());

tempObservable
        .map(user -> user.getId())
        .flatMap(id -> Observable.fromCallable(() ->
                client.getUserSettings(request.execute(id)))
                .subscribeOn(Schedulers.io()))
        .subscribe(userSettings -> {
               showUserSettings()
        }, throwable -> throwable.printStackTrace(), () -> System.out.println("Request completes"));

At first, we simply make a getUser network request. With first observable when we get a User object, we make another request for fetching UserSettings request. In the previous example, we have a map and flatMap operator, map operator provides you a function that it basically returns a different object and flatMap operator basically accepts an object and return a new observable. Finally, we get the userSettings object in subscribe method.

Below example shows how you can make two network request that is independent of each other.

Observable.merge(Observable.fromCallable(() -> client.updateUser(request.execute(user)))
                .subscribeOn(Schedulers.io()),
        Observable.fromCallable(() -> client.addNewUserComment(request.execute(user.getId)))
                .subscribeOn(Schedulers.io()))
        .subscribe(response -> System.out.println("Data inserted in to database.")
                , Throwable::printStackTrace);

Observable.merge is the static method for creating observable. In here it basically executes two network request simultaneously, when both request complete with success it will be called onNext, if it got an error it will be called the onError method.

RxJava provides many methods for converting the observable into other types.

Conversion of Observable.

From / ToFlowableObservableMaybeSingleCompleteable
FlowabletoObservable()elementAt()
reduce()
firstElement()
lastElement()
singleElement()
scan()
elementAt()
first()
firstOrError()
single()
singleOrError()
last()
lastOrError()
all()
any()
count()
ignoreElements()
ObservabletoFlowable()elementAt()
reduce()
firstElement()
lastElement()
singleElement()
scan()
elementAt()
first()
firstOrError()
single()
singleOrError()
last()
lastOrError()
all()
any()
ignoreElements()
MaybetoFlowable()toObservable()toSingle()
seruenceEqual()
toCompleteable()
SingletoFlowable()toObservable()toMaybe()toCompleteable()
CompleteabletoFlowable()toObservable()toMaybe()toSingle()
toSingleDefault()

Now it’s time to see how RxJava helps us to use this in the making of Android App. For this, we have to add another dependency to our build.gradle file.

// Rx java dependency
implementation 'io.reactivex.rxjava2:rxjava:2.1.8'

// Rx Android dependency
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'          // change version number with latest version.

RxAndroid

RxAndroid is an extension of RxJava. It provides feasibility to run code in the Main Thread of Android from Background Thread. RxAndroid is specifically for Android.

Let’s see a simple example of how to make a network request in a Background Thread and retrieving the response in Main Thread. For network request, we are using another popular library Retrofit. Now why I’m saying you this, because retrofit gives you this option of converting it automatically to an observable.

Below is the simple interface of retrofit with observable.

public interface ServiceUtil{
    
     @GET("user")
     Observable<User> getUser();
}

This is a basic interface of  Retrofit. If you want to see the example of how to create Retrofit and the interface properly, please see this example.

Now we just need to call this function in our activity.

disposable = serviceUtil.getUser()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(user -> {
                showUser(user);
        }, Throwable::printStackTrace, () -> System.out.println("Fetch User Successfully"));

You see in here when we subscribing to observable. We’re telling that execute our network request in a background thread. Another advantage of RxJava we can specify in which thread we want our response. So in Android, we only update views from Main Thread. That’s why we’re telling observed on in Main Thread. 

Subscribe method returns a disposable object. It’s a good approach that we dispose of it in onStop or onDestroy method, because of memory leak.

Below is the example how we can dispose of.

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

So, this is my demonstration about RxJava, although RxJava is much more than this I explain. I encourage you to read more about RxJava on their official website.

If you guys want to see how to work RxJava, Dagger and Retrofit see this example of my blog. Also, you can see complete example here on GitHub.

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

Thank you for being here.

The post RxJava with Examples | Reactive Programming for Beginners appeared first on Coding Infinite.

]]>
Dagger With Retrofit And RxJava Example | RecyclerView https://codinginfinite.com/dagger-retrofit-rxjava-example-recyclerview/ https://codinginfinite.com/dagger-retrofit-rxjava-example-recyclerview/#comments Wed, 11 Apr 2018 22:02:37 +0000 http://codinginfinite.com/?p=91 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...

The post Dagger With Retrofit And RxJava Example | RecyclerView appeared first on Coding Infinite.

]]>
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

The post Dagger With Retrofit And RxJava Example | RecyclerView appeared first on Coding Infinite.

]]>
https://codinginfinite.com/dagger-retrofit-rxjava-example-recyclerview/feed/ 3