【发布时间】:2020-11-15 10:25:33
【问题描述】:
kotlin coroutines version 1.3.8
kotlin 1.3.72
这是我第一次使用协程,并且我已经使用协程转换了我的 rxjava2。但由于这是我第一次想知道我是否遵循最佳做法。
-
我的一个问题是捕获异常,因为在 kotlin 中这可能是一种不好的做法,因为吞下异常可能会隐藏一个严重的错误。但是使用协程还有其他方法可以捕获错误。在 RxJava 中,使用 onError 很简单。
-
这会让测试更容易吗?
-
这是对挂起函数的正确使用吗?
非常感谢您的任何建议。
interface PokemonService {
@GET(EndPoints.POKEMON)
suspend fun getPokemons(): PokemonListModel
}
如果响应太慢或某些网络错误,将在 10 秒后超时的交互器
class PokemonListInteractorImp(private val pokemonService: PokemonService) : PokemonListInteractor {
override suspend fun getListOfPokemons(): PokemonListModel {
return withTimeout(10_000) {
pokemonService.getPokemons()
}
}
}
在我的视图模型中,我使用 viewModelScope。只是想知道我是否应该捕获异常。
fun fetchPokemons() {
viewModelScope.launch {
try {
shouldShowLoading.value = true
pokemonListLiveData.value = pokemonListInteractor.getListOfPokemons()
}
catch(error: Exception) {
errorMessage.value = error.localizedMessage
}
finally {
shouldShowLoading.value = false
}
}
}
在我的片段中,我只是观察实时数据并填充适配器。
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
}
【问题讨论】:
标签: kotlin try-catch kotlin-coroutines