Hey folks! I'm starting with Flows and have a ques...
# coroutines
a
Hey folks! I'm starting with Flows and have a question, especifically with StateFlow. I found a use case that I'm not sure whether it's a good one or not. I'm writing a simple paging system for an Android App, where I inform the VM of the current latest visible item in the adapter, and then this calls the repository to check whether it has the current page or it needs to go the server to get the next one. I initially did it with a regular
launch
, 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:
Copy code
recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    viewModel.lastVisible.value = layoutManager.findLastVisibleItemPosition()
                }
            })
Copy code
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.
👍 1