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.
So as per the RxJava documentation an interval is :
create an Observable that emits a sequence of integers spaced by a given time interval
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 :
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.
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
Check out all the top articles at blog.mindorks.com