Skip to content

Instantly share code, notes, and snippets.

@Aldikitta
Created June 14, 2023 09:30
Show Gist options
  • Save Aldikitta/ea2a3a2667b7ee6d1505ae00818c1439 to your computer and use it in GitHub Desktop.
Save Aldikitta/ea2a3a2667b7ee6d1505ae00818c1439 to your computer and use it in GitHub Desktop.
fun <T> Flow<T>.asSallyResponseResourceFlow(): Flow<SallyResponseResource<T>> {
return this
.map<T, SallyResponseResource<T>> {
SallyResponseResource.Success(it)
}
.onStart { emit(SallyResponseResource.Loading(true)) }
.onCompletion { emit(SallyResponseResource.Loading(false)) }
.catch { error ->
val exception = when (error) {
is HttpException -> {
when (error.code()) {
in 400..499 -> {
ClientException(
message = "${Constant.CLIENT_ERROR}: ${error.code()}",
cause = error,
)
}
in 500..599 -> {
ServerException(
message = "${Constant.SERVER_ERROR}: ${error.code()}",
cause = error
)
}
else -> {
UnknownException(
message = "${Constant.HTTP_UNKNOWN_ERROR}: ${error.code()}",
cause = error
)
}
}
}
is IOException -> NetworkException(
message = Constant.NETWORK_ERROR,
cause = error
)
else -> AppException(
message = Constant.UNKNOWN_ERROR,
cause = error
)
}
val errorCode = when (error) {
is HttpException -> {
when (error.code()) {
in 400..499 -> {
"#ER${error.code()}"
}
in 500..599 -> {
"#ER${error.code()}"
}
else -> {
"#ER${error.code()}"
}
}
}
else -> {
error.cause?.message.toString()
}
}
emit(SallyResponseResource.Error(exception, errorCode))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment