Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Since the onScrollStateChanged(RecyclerView.SCROLL_STATE_IDLE) is not reliable,
* We should check the recyclerView.scrollState after fling instead
*
* ref. https://stackoverflow.com/questions/8140623/android-onscrollstatechanged-scroll-state-idle-sometimes-doesnt-fire
*/
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
scrollStateFlow.tryEmit(newState)
}
})
val scrollStateFlow = MutableSharedFlow<Int>(1, 1, BufferOverflow.DROP_OLDEST)
val fixedScrollIdleStateJob: Job? = null
scrollStateFlow.distinctUntilChanged().filter { it == RecyclerView.SCROLL_STATE_SETTLING }.onEach {
fixedScrollIdleStateJob?.cancel()
fixedScrollIdleStateJob = viewModel.viewModelScope.launch(Dispatchers.IO) {
delay(1500)
if (recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE) {
scrollStateFlow.emit(recyclerView.scrollState)
}
}
}.flowOn(Dispatchers.IO).launchIn(viewModel.viewModelScope)
scrollStateFlow.distinctUntilChanged().filter { it == RecyclerView.SCROLL_STATE_IDLE }.onEach {
// fixed idle state
}.launchIn(viewModel.viewModelScope)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment