Created
January 1, 2019 08:55
-
-
Save rezaiyan/02d6ca51884d8985e493c4972452e24b 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
package com.weembee.sdk.base | |
import retrofit2.HttpException | |
sealed class Result<out Any> { | |
data class Ok<T: Any>(val value: T): Result<T>() | |
data class NetworkError(val code: Int): Result<Nothing>() | |
data class Error(val throwable: Throwable): Result<Nothing>() | |
} | |
inline fun <T: Any> resultOrError(block: () -> T): Result<T> { | |
return try { | |
Result.Ok(block()) | |
} catch (httpException: HttpException) { | |
Result.NetworkError(httpException.code()) | |
} catch (throwable: Throwable) { | |
Result.Error(throwable) | |
} | |
} |
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
package com.weembee.sdk.base | |
import retrofit2.Call | |
import retrofit2.Callback | |
import retrofit2.HttpException | |
import retrofit2.Response | |
import kotlin.coroutines.resume | |
import kotlin.coroutines.resumeWithException | |
import kotlin.coroutines.suspendCoroutine | |
private suspend fun <T> Call<T>.await(): T = suspendCoroutine { continuation -> | |
enqueue(object : Callback<T> { | |
override fun onFailure(call: Call<T>, t: Throwable) { | |
continuation.resumeWithException(t) | |
} | |
override fun onResponse(call: Call<T>, response: Response<T>) { | |
if (response.isSuccessful) | |
continuation.resume(response.body()!!) | |
else | |
continuation.resumeWithException(HttpException(response)) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment