Error Handling with RecyclerView when we get empty or null response from BE.

 Error Handling Best Practices 

When there is no network when it is launched, it shows a blank screen -> this is not a good user experience in app. 

So we will see some of the basics of error handling. 

  • If network is not available -> we show connection error icon
  • If fetching the data -> we show the loading animation 

We need to create a LiveData in ViewModel to represent the status of our web request. 

enum class MyApiStatus { LOADING, ERROR, DONE }
// The external immutable LiveData for the request status
val status: LiveData<MyApiStatus>
get() = _status
coroutineScope.launch {

var getPropertiesDeferred = MyApi.retrofitService.getProperties()
// surround the Retrofit code with try/catch, and set _response appropriately
try {
_status.value = MyApiStatus.LOADING
var listResult = getPropertiesDeferred.await()
_status.value = MyApiStatus.DONE
_properties.value = listResult
_response.value = "Success: ${listResult?.size} My properties retrieved"
}catch (t: Throwable){
_response.value = "Failure:" + t.message
_status.value = MyApiStatus.ERROR
_properties.value = emptyList()
}
}
@BindingAdapter("myApiStatus")
fun bindStatus(statusImageView: ImageView, status: MyApiStatus?) {
when (status) {
MyApiStatus.LOADING -> {
statusImageView.visibility = View.VISIBLE
statusImageView.setImageResource(R.drawable.loading_animation)
}
MyApiStatus.ERROR -> {
statusImageView.visibility = View.VISIBLE
statusImageView.setImageResource(R.drawable.ic_connection_error)
}
MyApiStatus.DONE -> {
statusImageView.visibility = View.GONE
}
}
}
<ImageView
android:id="@+id/status_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:myApiStatus="@{viewModel.status}" />





Comments

Popular Posts