NetworkBoundResource helper class without Room
Here is my attempt after a long while!
abstract class NetworkOnlyResource<ResultType, RequestType>
@MainThread constructor(private val appExecutors: AppExecutors) {
private val result = MediatorLiveData<Resource<ResultType>>() //List<Repo>
private val request = MediatorLiveData<Resource<RequestType>>() //RepoSearchResponse
init {
result.value = Resource.loading(null)
fetchFromNetwork()
}
@MainThread
private fun setResultValue(newValue: Resource<ResultType>) {
if (result.value != newValue) {
result.value = newValue
}
}
private fun fetchFromNetwork() {
val apiResponse = createCall()
result.addSource(apiResponse) { response ->
result.removeSource(apiResponse)
response?.let {
if (response.isSuccessful) {
appExecutors.diskIO().execute({
val requestType = processResponse(response)
val resultType = processResult(requestType)
appExecutors.mainThread().execute({
setResultValue(Resource.success(resultType))
}
)
})
} else {
val errorMessage = when (response.errorThrowable) {
is HttpException -> "An error has occurred: ${response.errorThrowable.code()} Please try again."
is SocketTimeoutException -> "A timeout error has occurred, please check your internet connection and try again"
is IOException -> "An IO error has occurred, most likely a network issue. Please check your internet connection and try again"
is UnauthorizedCredentialsException -> "This user name or password is not recognized"
else -> {
response.errorMessage
}
}
Timber.e(errorMessage)
errorMessage?.let {
val requestType = processResponse(response)
val resultType = processResult(requestType)
setResultValue(Resource.error(errorMessage, resultType, response.errorThrowable))
}
onFetchFailed()
}
}
}
}
protected open fun onFetchFailed() {}
fun asLiveData() = result as LiveData<Resource<ResultType>>
@WorkerThread
protected open fun processResponse(response: ApiResponse<RequestType>) = response.body
@WorkerThread
protected abstract fun processResult(item: RequestType?): ResultType?
@MainThread
protected abstract fun createCall(): LiveData<ApiResponse<RequestType>>
}
The processResult()
function allows you to transform a successful RequestType into a ResultType. It seems to work for me but would love any feedback from someone that knows what they are doing :)
Fyi Yigit has since updated the NetworkBoundResource with better error handling which should also work here in the not-successful 'else' statement.
Here's my version which I wrote sometime back:
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MediatorLiveData
import android.support.annotation.MainThread
/**
* A generic class to send loading event up-stream when fetching data
* only from network.
*
* @param <RequestType>
</RequestType></ResultType> */
abstract class NetworkResource<RequestType> @MainThread constructor() {
/**
* The final result LiveData
*/
private val result = MediatorLiveData<Resource<RequestType>>()
init {
// Send loading state to UI
result.value = Resource.loading()
fetchFromNetwork()
}
/**
* Fetch the data from network and then send it upstream to UI.
*/
private fun fetchFromNetwork() {
val apiResponse = createCall()
// Make the network call
result.addSource(apiResponse) { response ->
result.removeSource(apiResponse)
// Dispatch the result
response?.apply {
when {
status.isSuccessful() -> setValue(this)
else -> setValue(Resource.error(errorMessage))
}
}
}
}
@MainThread
private fun setValue(newValue: Resource<RequestType>) {
if (result.value != newValue) result.value = newValue
}
fun asLiveData(): LiveData<Resource<RequestType>> {
return result
}
@MainThread
protected abstract fun createCall(): LiveData<Resource<RequestType>>
}
The problem is that any loaded data have to go through the database first, then loading it from the database to the UI, as NetworkBoundResource
does. Consequently, What I did is to decouple the persistent database and create a temporary field to load from.
For example if I wanted to edit the original search method, I would suggest:
public LiveData<Resource<List<Repo>>> search(String query) {
return new NetworkBoundResource<List<Repo>, RepoSearchResponse>(appExecutors) {
// Temp ResultType
private List<Repo> resultsDb;
@Override
protected void saveCallResult(@NonNull RepoSearchResponse item) {
// if you don't care about order
resultsDb = item.getItems();
}
@Override
protected boolean shouldFetch(@Nullable List<Repo> data) {
// always fetch.
return true;
}
@NonNull
@Override
protected LiveData<List<Repo>> loadFromDb() {
if (resultsDb == null) {
return AbsentLiveData.create();
}else {
return new LiveData<List<Repo>>() {
@Override
protected void onActive() {
super.onActive();
setValue(resultsDb);
}
};
}
}
@NonNull
@Override
protected LiveData<ApiResponse<RepoSearchResponse>> createCall() {
return githubService.searchRepos(query);
}
@Override
protected RepoSearchResponse processResponse(ApiResponse<RepoSearchResponse> response) {
RepoSearchResponse body = response.body;
if (body != null) {
body.setNextPage(response.getNextPage());
}
return body;
}
}.asLiveData();
}
I ran it and it works.
Edit: I made another simpler class to handle that (There is another answer here by Daniel Wilson has more feature and is updated).
However, this class has no dependencies and is converted to the basics to make fetch response only:
abstract class NetworkBoundResource<RequestType> {
private val result = MediatorLiveData<Resource<RequestType>>()
init {
setValue(Resource.loading(null))
fetchFromNetwork()
}
@MainThread
private fun setValue(newValue: Resource<RequestType>) {
if (result.value != newValue) {
result.value = newValue
}
}
private fun fetchFromNetwork() {
val apiResponse = createCall()
result.addSource(apiResponse) { response ->
result.removeSource(apiResponse)
when (response) {
is ApiSuccessResponse -> {
setValue(Resource.success(processResponse(response)))
}
is ApiErrorResponse -> {
onFetchFailed()
setValue(Resource.error(response.errorMessage, null))
}
}
}
}
protected fun onFetchFailed() {
}
fun asLiveData() = result as LiveData<Resource<RequestType>>
@WorkerThread
protected open fun processResponse(response: ApiSuccessResponse<RequestType>) = response.body
@MainThread
protected abstract fun createCall(): LiveData<ApiResponse<RequestType>>
}
So when using it, only one method could be implemented createCall()
:
fun login(email: String, password: String) = object : NetworkBoundResource<Envelope<User>>() {
override fun createCall() = api.login(email, password)
}.asLiveData()