Android: Infinite Carousel with Coroutines and ViewPager1

Carousel by

Auto-scrolling carousels seem like something reminiscent of e-commerce websites, not something you would usually see on mobile, and maybe that’s why there aren’t many up-to-date implementations out there (at least for Android).

But at Woov we found a case where it looks good, doesn’t distract the user from other action/content on the screen, and highlights content.

Let’s see what the end result was and how we implemented it.

Auto-scrolling carousel

How to scroll forever

The first problem I tackled to achieve this result was doing the infinitely auto-scrolling in a thread-safe way.

Coroutines seemed like the way to go from the beginning since with it I can dispatch some work to be done every X seconds respecting the view’s lifecycle.

The method above is a simple extension function for ViewPager2, it basically waits for a while, then scroll to the next item or back to the first one if the current item is the last one, then it calls itself again, thus doing it forever.

Then you might ask: won’t it leak when the user navigates away from the screen or puts it in the background? Don’t you need to check and cancel it?

And the answers are no and no. Thanks to coroutines and LifecycleScope.

Auto-scroll extension function

By launching the scrollIndefinitely suspending function with LifecycleCoroutineScope, we ensure it will live only during the scope lifecycle and will get canceled once the view gets destroyed.

But that is not enough, we also want to only run the scrolling when the screen is in the foreground, and that’s when launchWhenResume comes to play.

Let’s look at its implementation:

Docs for launchWhenResumed

It handles the lifecycle events for us, only running when the lifecycle is resumed, on practical terms, when the screen is visible.

Using it is pretty simple:

Setting the auto-scrolling with the view pager

This implementation already does the trick for the ever-scrolling carousel, but one thing you will notice is that when it reaches the last item, it scrolls all the way back to the first one.
It would be nicer if it just kept scrolling forward, right?

How to make it always go forward

Considering this, my full of tricks colleague Nermin Turkovic came up with a quick solution on the ViewPagerAdapter itself.

This basically “tricks” the adapter into thinking there are infinite pages while using the actual list for creating the fragments.

That’s all folks.

Feel free to follow on social media:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store