Created
November 8, 2019 05:40
-
-
Save herisulistiyanto/edbe66ed39f1a7ef74eb218f0c09cad6 to your computer and use it in GitHub Desktop.
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
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