Skip to content

Instantly share code, notes, and snippets.

@herisulistiyanto
Created November 8, 2019 05:40
Show Gist options
  • Save herisulistiyanto/edbe66ed39f1a7ef74eb218f0c09cad6 to your computer and use it in GitHub Desktop.
Save herisulistiyanto/edbe66ed39f1a7ef74eb218f0c09cad6 to your computer and use it in GitHub Desktop.
abstract class BaseDataSource {
protected suspend fun <T> getResult(call: suspend () -> Response<T>): ResponseResult<ResponseWrapper<T>> {
try {
val response = call()
if (response.isSuccessful) {
val body = response.body()
if (null != body) return ResponseResult.Success(ResponseWrapper(body, null))
}
return error("${response.code()} ${response.message()}")
} catch (e: Exception) {
return error(e.message ?: e.toString())
}
}
private fun <T> error(msg: String): ResponseResult<ResponseWrapper<T>> {
Timber.e(msg)
return ResponseResult.Error(ResponseWrapper(null, msg))
}
}
// produce LiveData
fun <T> resultLiveData(scope: CoroutineScope, call: suspend () -> ResponseResult<T>): LiveData<ResponseResult<T>> {
return liveData(scope.coroutineContext) {
emit(ResponseResult.Loading)
withContext(Dispatchers.IO) {
emit(call.invoke())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment