Skip to content

Instantly share code, notes, and snippets.

@ercnksgl
Last active September 20, 2022 13:50
Show Gist options
  • Save ercnksgl/b21cd240472677490de7ee2c3d1e94db to your computer and use it in GitHub Desktop.
Save ercnksgl/b21cd240472677490de7ee2c3d1e94db to your computer and use it in GitHub Desktop.
NetworkUtils.kt for sealed class
import com.ercnksgl.sealedtest.data.network.Result
import com.ercnksgl.sealedtest.data.network.response.ApiError
import com.ercnksgl.sealedtest.data.network.response.ApiError.UnexpectedError
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.Response
class NetworkUtils {
suspend fun <T : Any> request(onRequest: suspend () -> Response<T>): Result<T> =
withContext(Dispatchers.IO) {
safeApiCall {
with(onRequest()) {
when {
isSuccessful && body() != null -> {
Result.Success(body() as T)
}
else -> {
Result.Error(ApiError.ServerError(errorBody()?.string())
}
}
}
}
private suspend fun <T : Any> safeApiCall(call: suspend () -> Result<T>): Result<T> {
return try {
call()
} catch (e: Exception) {
Result.Error(ApiError.UnexpectedError())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment