Last active
September 20, 2022 13:50
-
-
Save ercnksgl/b21cd240472677490de7ee2c3d1e94db to your computer and use it in GitHub Desktop.
NetworkUtils.kt for sealed class
This file contains hidden or 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
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