Created
July 3, 2019 19:46
-
-
Save Chrispassold/31c3c77d148b201b0d242ee0daa4d3a5 to your computer and use it in GitHub Desktop.
Same logic of NetworkBoundResource but only with network data
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
import android.content.Context | |
import io.reactivex.Flowable | |
import io.reactivex.android.schedulers.AndroidSchedulers | |
import io.reactivex.exceptions.Exceptions | |
import io.reactivex.schedulers.Schedulers | |
import retrofit2.HttpException | |
import retrofit2.Response | |
import timber.log.Timber | |
import java.io.IOException | |
abstract class NetworkOnlyBoundResource<ResultType>(context: Context) { | |
private val result: Flowable<Resource<ResultType>> | |
init { | |
// Lazy network observable. | |
val networkObservable = Flowable.defer { | |
createCall() | |
// Request API on IO Scheduler | |
.subscribeOn(Schedulers.io()) | |
// Read/Write to disk on Computation Scheduler | |
.observeOn(Schedulers.computation()) | |
.onErrorReturn { throwable: Throwable -> | |
Timber.e(throwable, "HttpErrorHandler") | |
when (throwable) { | |
is HttpException -> { | |
throw Exceptions.propagate(NetworkExceptions.getNoServerConnectivityError(context)) | |
} | |
is IOException -> { | |
throw Exceptions.propagate(NetworkExceptions.getNoNetworkConnectivityError(context)) | |
} | |
else -> { | |
throw Exceptions.propagate(NetworkExceptions.getUnexpectedError(context)) | |
} | |
} | |
} | |
.flatMap { | |
if (it.isSuccessful) { | |
processResponse(it) | |
} else { | |
Flowable.error(Exception(it.errorBody()?.string())) | |
} | |
} | |
} | |
result = networkObservable | |
.map<Resource<ResultType>> { Resource.Success(it) } | |
.onErrorReturn { Resource.Failure(it) } | |
// Read results in Android Main Thread (UI) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.startWith(Resource.Loading()) | |
} | |
fun asFlowable(): Flowable<Resource<ResultType>> { | |
return result | |
} | |
private fun processResponse(response: Response<ResultType>): Flowable<ResultType> { | |
return Flowable.just(response.body()!!) | |
} | |
protected abstract fun createCall(): Flowable<Response<ResultType>> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment