Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StateFlow fetching the same data again on Back Navigation

I am working with RecyclerView and using Retrofit to fetch the data from Server. I am using Kotlin with MVVM Design Pattern. I have used LiveData it was working fine. But with Stateflow causing issues when we navigate to another Fragment and Comes back to the Same Fragment again. It just fetches the same data again. Below is the code for ViewModel and the observer:

//View Model

private val _allTimeSheetsResponse =
        MutableStateFlow<ResponsesResult<AllTimeSheetsResponse>>(ResponsesResult.Empty)
    val allTimeSheetsResponse : StateFlow<ResponsesResult<AllTimeSheetsResponse>> get() = _allTimeSheetsResponse

    fun getAllTimeSheets(auth: String) =
        viewModelScope.launch {
            timeSheetsRepository.getAllTimeSheets(auth).collect {
                _allTimeSheetsResponse.value = it
            }
        }

//Observer

lifecycleScope.launchWhenStarted{
            timeSheetsViewModel.allTimeSheetsResponse.collect { timeSheetsResponse ->
                when (timeSheetsResponse) {
                    is ResponsesResult.Loading -> binding.progressBarLayout.show()
                    is ResponsesResult.Failure -> {
                        binding.progressBarLayout.gone()
                        binding.nothingFoundLayout.show()
                        handleApiError(timeSheetsResponse)
                    }
                    is ResponsesResult.Success -> {
                        binding.progressBarLayout.gone()
                        if (timeSheetsResponse.value.payload.isNotEmpty()) {
                            showAllTimeSheetsRecyclerAdapter.submitList(timeSheetsResponse.value.payload)
                        } else {
                            binding.nothingFoundLayout.show()
                        }
                    }
                    else -> Unit
                }
            }
        }
like image 235
markhor1999 Avatar asked Jul 14 '26 23:07

markhor1999


1 Answers

Because you call getAllTimeSheets many times (eg. onCreateView or onViewCreated). Trying call it when accessing allTimeSheetsResponse` for the first time.

like image 91
Petrus Nguyễn Thái Học Avatar answered Jul 17 '26 16:07

Petrus Nguyễn Thái Học



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!