override fun getMovies(page: Int): Flow<Resource<List<Movie>>> = flow {
try {
val nowPlayingMovies = api.getMovies(HttpRoutes.NOW_PLAYING, page).results.map {
it.toMovie()
}
val popularMovies = api.getMovies(HttpRoutes.POPULAR, page).results.map {
it.toMovie()
}
val movies = listOf(nowPlayingMovies, popularMovies, )
movies.forEach {
emit(Resource.Success(it))
}
} catch (e: HttpException) {
emit(Resource.Error<List<Movie>>(context.getString(R.string.sth_wrong)))
} catch (e: IOException) {
emit(Resource.Error<List<Movie>>(context.getString(R.string.check_connection)))
}
}
private fun getMovies() {
moviesUseCases.getMoviesUseCase().onEach { result ->
when (result) {
is Resource.Success -> {
_state.value = MainScreenState(
nowPlayingMovies = result.data?.shuffled() ?: emptyList(),
popularMovies = result.data?.shuffled() ?: emptyList(),
topRatedMovies = result.data?.shuffled() ?: emptyList(),
upcomingMovies = result.data?.shuffled() ?: emptyList(),
isLoading = false
)
}
is Resource.Error -> {
_state.value = MainScreenState(
error = result.message ?: "An unexpected error occurred"
)
}
is Resource.Loading -> {
_state.value = MainScreenState(isLoading = true)
}
}
}.launchIn(viewModelScope)
}