Skip to content

Instantly share code, notes, and snippets.

@yongjhih
Last active September 8, 2022 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yongjhih/ff9349dd4d941897be87442313fa3260 to your computer and use it in GitHub Desktop.
Save yongjhih/ff9349dd4d941897be87442313fa3260 to your computer and use it in GitHub Desktop.
/**
* 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