Last active
September 8, 2022 18:38
-
-
Save yongjhih/ff9349dd4d941897be87442313fa3260 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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