Skip to content

Instantly share code, notes, and snippets.

@nknr
Created February 23, 2021 09:54
Show Gist options
  • Save nknr/34e4a946ea8a42464a2b9848c04f62ec to your computer and use it in GitHub Desktop.
Save nknr/34e4a946ea8a42464a2b9848c04f62ec to your computer and use it in GitHub Desktop.
Coroutine network helper
enum class NetworkStatus {
INITIAL,SUCCESS, ERROR, UNAUTHORIZED
}
suspend fun <T> safeApiCall(dispatcher: CoroutineDispatcher, apiCall: suspend () -> T): Resource<T> {
return withContext(dispatcher) {
try {
Resource.success(apiCall.invoke())
} catch (exception:Exception) {
Timber.e("error $exception")
getResourceError(exception)
}
}
}
fun <T> getResourceError(error: Throwable?): Resource<T> {
Timber.e("error %s", error.toString())
return when (error) {
is SocketTimeoutException -> Resource.error("Oooops! We couldn’t capture your request in time. Please try again.")
is IOException -> Resource.error("Please, check internet connection on your smartphone to sync data.")
is HttpException -> unsuccessfulResponse(error.response()!!.code())
else -> Resource.error("Oops! We hit an error. Try again later.")
}
}
private fun <T> unsuccessfulResponse(statusCode: Int): Resource<T> {
return when (statusCode) {
404 -> Resource.error("Api not found")
401 -> Resource.unauthorized("Unauthorised access")
500 -> Resource.error("Server broken")
503 -> Resource.error("Service Unavailable")
else -> Resource.error("Oops! We hit an error. Try again later.")
}
}
suspend fun login(apiRequest: ApiRequest):Resource<ApiResponse<List<User?>?>?>{
return safeApiCall(dispatcher){
restApi.login(apiRequest)
}
}
class Resource<T>(
private val networkStatus: NetworkStatus = NetworkStatus.INITIAL,
val data: T?,
val message: String = ""
) {
val isSuccess: Boolean
get() = networkStatus === NetworkStatus.SUCCESS && data != null
val isError: Boolean
get() = networkStatus === NetworkStatus.ERROR
val isUnauthorized:Boolean
get() = networkStatus === NetworkStatus.UNAUTHORIZED
companion object {
fun <T> success(data: T): Resource<T> {
return Resource(NetworkStatus.SUCCESS, data, "")
}
fun <T> error(msg: String, data: T? = null): Resource<T> {
return Resource(NetworkStatus.ERROR, data, msg)
}
fun <T> unauthorized(msg: String, data: T?=null): Resource<T> {
return Resource(NetworkStatus.ERROR, data, msg)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment