antonioleiva
09/29/2020, 9:10 AMlaunch
, but of course this is not a good idea, because the latest visible item can change several times before the request is finished, and it will run the request to the same page several times too.
So I used a StateFlow in the ViewModel, which is public and mutable, so that the Activity can modify the value with the latest visible item, and then I collect it in the ViewModel and run the request to the repository. As the next value is not processed until the previous one is processed, it works perfectly. But I'm not sure if I'm "hacking" the system somehow 😅
Here's the code for reference:
recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
viewModel.lastVisible.value = layoutManager.findLastVisibleItemPosition()
}
})
init {
viewModelScope.launch {
lastVisible.collect { value ->
repository.checkRequireNewPage(value)
_spinner.value = false
}
}
}
That _spinner
is also a MutableStateFlow that I'm then exposing with a public non mutable property, which I think is the regular use of StateFlow (an equivalent to LiveData). That's why I'm not sure if my other code is right or I'm missing something.