Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class FakeHomeRepository : HomeRepository {
page: Int,
onStart: () -> Unit,
onComplete: () -> Unit,
onLastPageReached: () -> Unit,
onError: (String?) -> Unit,
): Flow<List<Pokemon>> = flowOf()
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ interface HomeRepository {
page: Int,
onStart: () -> Unit,
onComplete: () -> Unit,
onLastPageReached: () -> Unit,
onError: (String?) -> Unit,
): Flow<List<Pokemon>>
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ class HomeRepositoryImpl @Inject constructor(
page: Int,
onStart: () -> Unit,
onComplete: () -> Unit,
onLastPageReached: () -> Unit,
onError: (String?) -> Unit,
) = flow {
var pokemons = pokemonDao.getPokemonList(page).asDomain()
Expand All @@ -58,6 +59,10 @@ class HomeRepositoryImpl @Inject constructor(
*/
val response = pokedexClient.fetchPokemonList(page = page)
response.suspendOnSuccess {
if (data.next == null) {
onLastPageReached()
}

pokemons = data.results
pokemons.forEach { pokemon -> pokemon.page = page }
pokemonDao.insertPokemonList(pokemons.asEntity())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@ class HomeViewModel @Inject constructor(
) : BaseViewModel() {

internal val uiState: ViewModelStateFlow<HomeUiState> = viewModelStateFlow(HomeUiState.Loading)
private var isLastPageReached = false

private val pokemonFetchingIndex: MutableStateFlow<Int> = MutableStateFlow(0)
val pokemonList: StateFlow<List<Pokemon>> = pokemonFetchingIndex.flatMapLatest { page ->
homeRepository.fetchPokemonList(
page = page,
onStart = { uiState.tryEmit(key, HomeUiState.Loading) },
onComplete = { uiState.tryEmit(key, HomeUiState.Idle) },
onLastPageReached = { isLastPageReached = true },
onError = { uiState.tryEmit(key, HomeUiState.Error(it)) },
)
}.stateIn(
Expand All @@ -52,7 +54,7 @@ class HomeViewModel @Inject constructor(
)

fun fetchNextPokemonList() {
if (uiState.value != HomeUiState.Loading) {
if (uiState.value != HomeUiState.Loading && !isLastPageReached) {
pokemonFetchingIndex.value++
}
}
Expand Down
Loading