Last active
April 22, 2019 08:38
-
-
Save jishindev/fc947721b07a4700ff192e1fe80c0fc7 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
typealias NetworkCall<R> = suspend () -> Response<R> | |
typealias DbCall<R> = suspend () -> R | |
typealias DbSave<R> = suspend (R) -> Unit | |
open class BaseRepo { | |
suspend inline fun <R : Any, reified E> loadData( | |
noinline dbCall: DbCall<R>? = null, | |
noinline dbSave: DbSave<R>? = null, | |
noinline networkCall: NetworkCall<R>? = null | |
): MutableLiveData<Resource<R, E>> { | |
val result: MutableLiveData<Resource<R, E>> = MutableLiveData() | |
// From the db | |
dbCall?.let { result.postValue(performDbCall(it)) } | |
// Load from network | |
networkCall?.let { | |
result.postValue(performNetworkCall(networkCall)) | |
if (dbSave != null && result.value is Resource.Success) { | |
(result.value as? Resource.Success)?.data?.let { | |
dbSave.invoke(it) | |
} | |
} | |
} | |
return result | |
} | |
suspend inline fun <R : Any, reified E> performNetworkCall( | |
crossinline call: NetworkCall<R> | |
): Resource<R, E> = coroutineScope { | |
Timber.i("performNetworkCall() called with: call") | |
var result: Resource<R, E> | |
try { | |
if (isConnected()) { | |
val response = call.invoke() | |
val body = response.body() | |
if (response.isSuccessful && body != null) { | |
result = Resource.Success(body) | |
} else { | |
result = Resource.Error(response.errorBody()?.getError<E>()) | |
} | |
Timber.d("performNetworkCall: result: $result") | |
} else { | |
result = Resource.Error(exception = NoConnectionException("Not connected to the internet")) | |
} | |
} catch (e: Exception) { | |
e.printStackTrace() | |
result = Resource.Error(exception = e) | |
} | |
Timber.d("performNetworkCall() result: $result") | |
result | |
} | |
suspend inline fun <R : Any, reified E> performDbCall( | |
crossinline call: DbCall<R> | |
): Resource<R, E> { | |
var result: Resource<R, E> | |
try { | |
result = Resource.Cached(call()) | |
} catch (e: Exception) { | |
e.printStackTrace() | |
result = Resource.Error(exception = e) | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment