Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Same logic of NetworkBoundResource but only with network data
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
You can’t perform that action at this time.