Last active
October 4, 2019 17:33
-
-
Save mitchtabian/c13cb90859432744ff1c81ef22c18c04 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
fun getAccountProperties(authToken: AuthToken): LiveData<DataState<AccountViewState>> { | |
return object: NetworkBoundResource<AccountProperties, AccountProperties, AccountViewState>( | |
sessionManager.isConnectedToTheInternet(), | |
true, | |
true | |
){ | |
// if network is down, view the cache and return | |
override suspend fun createCacheRequestAndReturn() { | |
withContext(Dispatchers.Main){ | |
// finishing by viewing db cache | |
result.addSource(loadFromCache()){ viewState -> | |
onCompleteJob(DataState.data(viewState, null)) | |
} | |
} | |
} | |
override suspend fun handleApiSuccessResponse(response: ApiSuccessResponse<AccountProperties>) { | |
updateLocalDb(response.body) | |
withContext(Dispatchers.Main){ | |
// finishing by viewing db cache | |
result.addSource(loadFromCache()){ viewState -> | |
onCompleteJob(DataState.data(viewState, null)) | |
} | |
} | |
} | |
override fun loadFromCache(): LiveData<AccountViewState> { | |
return accountPropertiesDao.searchByPk(authToken.account_pk!!) | |
.switchMap { | |
object: LiveData<AccountViewState>(){ | |
override fun onActive() { | |
super.onActive() | |
value = AccountViewState(it) | |
} | |
} | |
} | |
} | |
override suspend fun updateLocalDb(cacheObject: AccountProperties?) { | |
cacheObject?.let { | |
accountPropertiesDao.updateAccountProperties( | |
cacheObject.pk, | |
cacheObject.email, | |
cacheObject.username | |
) | |
} | |
} | |
override fun createCall(): LiveData<GenericApiResponse<AccountProperties>> { | |
return openApiMainService | |
.getAccountProperties( | |
"Token ${authToken.token!!}" | |
) | |
} | |
override fun setJob(job: Job) { | |
repositoryJob?.cancel() | |
repositoryJob = job | |
} | |
}.asLiveData() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment