Skip to content

Commit

Permalink
Refactor previous onSuccess()
Browse files Browse the repository at this point in the history
  • Loading branch information
skydoves committed Jun 2, 2021
1 parent 48cc223 commit 3022b35
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import com.skydoves.whatif.whatIfNotNull
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import javax.inject.Inject

class DetailRepository @Inject constructor(
Expand All @@ -40,7 +41,7 @@ class DetailRepository @Inject constructor(
@WorkerThread
fun fetchPokemonInfo(
name: String,
onSuccess: () -> Unit,
onComplete: () -> Unit,
onError: (String?) -> Unit
) = flow<PokemonInfo?> {
val pokemonInfo = pokemonInfoDao.getPokemonInfo(name)
Expand All @@ -54,7 +55,6 @@ class DetailRepository @Inject constructor(
data.whatIfNotNull { response ->
pokemonInfoDao.insertPokemonInfo(response)
emit(response)
onSuccess()
}
}
// handle the case when the API request gets an error response.
Expand All @@ -68,7 +68,6 @@ class DetailRepository @Inject constructor(
.onException { onError(message) }
} else {
emit(pokemonInfo)
onSuccess()
}
}.flowOn(Dispatchers.IO)
}.onCompletion { onComplete() }.flowOn(Dispatchers.IO)
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ class MainRepository @Inject constructor(

@WorkerThread
fun getPokemonList(
onSuccess: () -> Unit,
onStart: () -> Unit,
onError: (String?) -> Unit
) = pokemonDao.getPokemonList()
.onStart { onSuccess() }
.onStart { onStart() }
.catch { onError(it.localizedMessage) }
.flowOn(Dispatchers.IO)
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class DetailViewModel @AssistedInject constructor(

private val pokemonInfoFlow = detailRepository.fetchPokemonInfo(
name = pokemonName,
onSuccess = { isLoading = false },
onComplete = { isLoading = false },
onError = { errorMessage = it }
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class MainViewModel @Inject constructor(
) : LiveCoroutinesViewModel() {

private val pokemonListFlow = mainRepository.getPokemonList(
onSuccess = { isLoading = false },
onStart = { isLoading = false },
onError = { errorMessage = it }
)

Expand Down

0 comments on commit 3022b35

Please sign in to comment.