kotlin coroutines version 1.3.8
kotlin 1.3.72
This is the first time I am using coroutines and I have converted my rxjava2 with using coroutines. But as this is my first time I am wondering if I am following best practices.
One question I have is catching the exceptions, as in kotlin this could be bad practice as swallowing exceptions might hide an servious bug. But using coroutines is there any other way to capture errors. In RxJava this is simple using the onError.
Would this make it easier for testing?
Is this the correct use of suspend functions?
Many thanks for any suggestions.
interface PokemonService {
@GET(EndPoints.POKEMON)
suspend fun getPokemons(): PokemonListModel
}
Interactor that will timeout after 10 seconds if the response is too slow or some network error
class PokemonListInteractorImp(private val pokemonService: PokemonService) : PokemonListInteractor {
override suspend fun getListOfPokemons(): PokemonListModel {
return withTimeout(10_000) {
pokemonService.getPokemons()
}
}
}
Inside my view model I use the viewModelScope. Just wondering if I should be catching exceptions.
fun fetchPokemons() {
viewModelScope.launch {
try {
shouldShowLoading.value = true
pokemonListLiveData.value = pokemonListInteractor.getListOfPokemons()
}
catch(error: Exception) {
errorMessage.value = error.localizedMessage
}
finally {
shouldShowLoading.value = false
}
}
}
In my fragment I am just observing the live data and populating the adapter.
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
bindings = FragmentPokemonListBinding.inflate(inflater, container, false)
setupAdapter()
pokemonViewModel.registerPokemonList().observe(viewLifecycleOwner, Observer { pokemonList ->
pokemonAdapter.populatePokemons(pokemonList.pokemonList)
})
return bindings.root
}