0

I have some problem with handling network response. Loading and Success state work perfectly fine but Error state doesn't work. When i simulate an error then triggered Loading and Success state not an Error. My code below.

Repository class

fun getMoviesStream(genreId: String?, sortBy: String): Flow<PagingData<Result>> {
        return Pager(
            config = PagingConfig(pageSize = MOVIES_PAGE_SIZE, enablePlaceholders = false),
            pagingSourceFactory = { MoviesPagingSource(api, genreId, sortBy) }
        ).flow
    }

ViewModel class

private val _moviesResponse = MutableStateFlow<Resource<PagingData<Result>>>(Resource.Loading())
val moviesResponse = _moviesResponse.asStateFlow()

fun getMovies(genreId: String?, sortBy: String) {
        viewModelScope.launch {
            _moviesResponse.value = Resource.Loading()
            moviesRepository.getMoviesStream(genreId, sortBy).cachedIn(viewModelScope)
                .catch { throwable ->
                    _moviesResponse.value = Resource.Error(
                        throwable.localizedMessage ?: "An unexpected error occurred"
                    )
                }
                .collect { result ->
                    delay(500)
                    _moviesResponse.value = Resource.Success(result)
                }

        }
    }

Fragment class

private fun requestMoviesData(genreId: String?, sortBy: String) {
        viewLifecycleOwner.lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                moviesViewModel.getMovies(genreId, sortBy)
                moviesViewModel.moviesResponse.collect { response ->
                    when (response) {
                        is Resource.Error -> {
                            Toast.makeText(
                                requireContext(),
                                response.message,
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                        is Resource.Loading -> {
                            binding.spinnerLoading.visibility = View.VISIBLE
                        }
                        is Resource.Success -> {
                            binding.spinnerLoading.visibility = View.GONE
                            response.data?.let { moviesAdapter.submitData(it) }
                        }
                    }
                }
            }
        }
    }
Anubis
  • 21
  • 2

1 Answers1

0

Please check the flow catch operator documentation. https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/catch.html

This operator is transparent to exceptions that occur in downstream flow and does not catch exceptions that are thrown to cancel the flow.

sajidjuneja
  • 184
  • 7