Created
June 14, 2023 09:30
-
-
Save Aldikitta/ea2a3a2667b7ee6d1505ae00818c1439 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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