[Pager] UI issues when using a timer
Describe the bug
I implemented 4 progress bars on my screen. Every progress bar lasts for 4 seconds and then it switches to the next progress bar and the HorizontalPager switches to the next screen at the same time (Instagram stories behaviour) and so on and it loops back to the first progress bar. I have a timer in my ViewModel that ticks every 100 milliseconds so the progress bar progress looks smooth.
To Reproduce
Steps to reproduce the behavior:
- Start app
- Observe text flicker in the Pager on some pages. (In the video it happens when it pages to the 2nd and 4th page)
Expected behavior
The pager would show the next page without any UI bugs.
Screenshots?
https://user-images.githubusercontent.com/1714041/123609974-6faadb80-d800-11eb-921c-448a53260ef3.mp4
Environment:
- Android OS version: [Android 9.0]
- Device: [Emulator, Google Pixel 2]
- Accompanist version: [v0.12.0]
Additional context
If I set my timer to tick with a lower rate (around 500 millis) the bug is not appearing. The bug doesn't happen on every page, looks like it's random.
I'll post my source code here:
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.org.MyViewModel
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.rememberPagerState
@OptIn(ExperimentalPagerApi::class)
@Composable
fun CarouselScreen(navController: NavController) {
val viewModel = viewModel<MyViewModel>()
val viewState = viewModel.viewState.collectAsState().value
val pagerState = rememberPagerState(
pageCount = viewState.progressMap.entries.size,
initialOffscreenLimit = 2,
infiniteLoop = true
)
LaunchedEffect(viewState.page) {
pagerState.animateScrollToPage(viewState.page)
}
VerticalPager(
state = pagerState,
modifier = Modifier
.fillMaxSize(),
dragEnabled = false
) { page ->
when (page) {
0 -> {
Page(
"My first text",
navController
)
}
1 -> {
Page(
"My second text that's\na little longer",
navController
)
}
2 -> {
Page(
"My third text that's\nalso pretty long",
navController
)
}
3 -> {
Page(
"My fourth text",
navController
)
}
}
}
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
Row(
modifier = Modifier
.padding(top = 70.dp)
) {
for (item in 0 until viewState.progressMap.entries.size) {
LinearProgressIndicator(
modifier = Modifier
.height(2.dp)
.width(12.dp),
color = Color.Black,
backgroundColor = Color.White,
progress = viewState.progressMap[item]!!
)
Spacer(modifier = Modifier.width(10.dp))
}
}
}
}
@Composable
fun Page(
description: String,
navController: NavController
) {
Box(
Modifier
.fillMaxSize()
.background(Color.LightGray, RectangleShape)
) {
Column(
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(bottom = 90.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = description,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h5,
modifier = Modifier.padding(bottom = 56.dp)
)
}
}
}
This is my ViewModel:
`
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
@OptIn(ExperimentalTime::class)
@HiltViewModel
class MyViewModel @Inject constructor() : ViewModel() {
private val _viewState: MutableStateFlow<ViewState> = MutableStateFlow(
ViewState(
mutableMapOf<Int, Float>().apply {
for (i in 0 until TOTAL_PAGES) {
put(i, 0f)
}
}
)
)
val viewState = _viewState.asStateFlow()
private val _intentChannel = Channel<Intent>(Channel.UNLIMITED)
val intentChannel = _intentChannel
init {
viewModelScope.launch {
interval(Duration.milliseconds(100)).collect {
val newProgressMillis = _viewState.value.progressMillis + TICK_DURATION
val normalizedProgressMillis: Long
if (newProgressMillis % TOTAL_CAROUSEL_DURATION == 0L) {
//We are at the end so reset everything
normalizedProgressMillis = 0
rescheduleProgressBars(0)
} else {
normalizedProgressMillis = newProgressMillis
}
val page =
(normalizedProgressMillis / Duration.milliseconds(PAGE_DURATION_MILLIS).inWholeMilliseconds).toInt()
val progress =
(normalizedProgressMillis / Duration.milliseconds(PAGE_DURATION_MILLIS).inWholeMilliseconds.toFloat()) - page
_viewState.value.progressMap[page] = progress
_viewState.value = _viewState.value.copy(
progressMillis = normalizedProgressMillis,
page = page
)
}
}
viewModelScope.launch {
_intentChannel.consumeAsFlow().collect { intent ->
when (intent) {
Intent.LeftClick -> {
val newPage = _viewState.value.page - 1
if (newPage < 0) {
val normalizedPage = _viewState.value.progressMap.entries.size - 1
rescheduleProgressBars(normalizedPage)
_viewState.value = _viewState.value.copy(
progressMillis = normalizedPage.toLong() * PAGE_DURATION_MILLIS,
page = normalizedPage
)
} else {
rescheduleProgressBars(newPage)
_viewState.value = _viewState.value.copy(
progressMillis = newPage.toLong() * PAGE_DURATION_MILLIS,
page = newPage
)
}
}
Intent.RightClick -> {
val newPage = _viewState.value.page + 1
if (newPage >= _viewState.value.progressMap.entries.size) {
rescheduleProgressBars(0)
_viewState.value = _viewState.value.copy(
progressMillis = 0,
page = 0
)
} else {
rescheduleProgressBars(newPage)
_viewState.value = _viewState.value.copy(
progressMillis = newPage.toLong() * PAGE_DURATION_MILLIS,
page = newPage
)
}
}
}
}
}
}
@OptIn(ExperimentalTime::class)
fun interval(period: Duration, initialDelay: Duration = Duration.ZERO) = flow {
delay(initialDelay)
while (true) {
emit(Unit)
delay(period)
}
}
private fun rescheduleProgressBars(currentPage: Int) {
_viewState.value.progressMap.apply {
for (i in 0 until _viewState.value.progressMap.entries.size) {
if (i < currentPage) {
put(i, 1f)
} else if (i > currentPage) {
put(i, 0f)
}
}
}
}
companion object {
const val TOTAL_PAGES = 4
const val PAGE_DURATION_MILLIS = 4000
const val TOTAL_CAROUSEL_DURATION = TOTAL_PAGES * PAGE_DURATION_MILLIS
const val TICK_DURATION = 100
}
}
Unfortunately I don't have the time to debug your custom animation code right now, but one thing that jumped out to me is that you're using animateScrollToPage(). If you're animating the value, you should really be using scrollToPage().
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.