Auto ViewPager slider using RxJava2

Hey folks,

This is my first article on medium and in this article I’ll tell you how to automate the viewpager so that it automatically slides to next screen after a predefined interval. And for this task I’ll use RxJava’s operator interval.

End result will look like this

So as per the RxJava documentation an interval is :

create an Observable that emits a sequence of integers spaced by a given time interval
Source : RxJava wiki
The Interval operator returns an Observable that emits an infinite sequence of ascending integers, with a constant interval of time of your choosing between emissions.

The interval operator takes in 2 parameters.

interval(time, TimeUnit)

So in this sample project I’ll have an activity which will contain a ViewPager and I’ll be using RxJava2 for automatic scroll and Glide for image loading for random images URL.

Mostly in application OnBoarding we use ViewPagers where we want to guide the user about the application using different images/screens. In those cases we need that the images should slide automatically.

If you don’t want to go through all the boring stuff then the project link is available at the end of the post.

If we have to do it by using only android components then we can do it like this :

Automating the ViewPager using Android Handler

In the above snippet we have created a Handler and providing it with a Runnable and then we are calling postDelayed on the Handler every 2 seconds so that it executes the same Runnable code again and again.

So now we have seen how to implement this by using default android components. Now we will see how to implement the same feature using RxJava’s interval operator.

Automating the ViewPager using RxJava’s interval operator

Please note that you should explicitly execute this code on observeOn(AndroidSchedulers.mainThread()) else you will get :

Caused by: java.lang.IllegalStateException: Must be called from main thread of fragment host

Don’t forget to unsubscribe/dispose your subscription/disposable. And implement onError incase you want to know the cause of your crash.

So that’s it for today you can find the sample project on github : RxViewPagerScroll

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.