Last active
March 26, 2021 10:17
-
-
Save vejei/e4f89970d3e384681fcb0c2e24198466 to your computer and use it in GitHub Desktop.
The NetoworkBoundSource which use RxJava instead of LiveData.
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 io.reactivex.Observable | |
import io.reactivex.android.schedulers.AndroidSchedulers | |
import io.reactivex.schedulers.Schedulers | |
import retrofit2.Response | |
abstract class NetworkBoundResource<ResultType, RequestType> { | |
private var result: Observable<Resource<ResultType>> | |
init { | |
result = loadFromLocal().flatMap { | |
if (shouldFetch(it)) { | |
fetchFromNetwork() | |
} else { | |
Observable.just(Resource.success(it)) | |
} | |
}.startWith(Resource.loading(null)) | |
} | |
private fun fetchFromNetwork(): Observable<Resource<ResultType>>? { | |
return createCall().subscribeOn(Schedulers.io()).flatMap { | |
Observable.just(it.body()?.data) | |
}.doOnNext { | |
if (it != null) { | |
saveCallResult(it) | |
} | |
}.observeOn(AndroidSchedulers.mainThread()).doOnError { | |
onFetchFailed() | |
}.observeOn(Schedulers.io()).flatMap { | |
loadFromLocal() | |
}.observeOn(AndroidSchedulers.mainThread()).map { | |
Resource.success(it) | |
}.onErrorReturn { | |
Resource.error("", null) | |
} | |
} | |
fun asObservable(): Observable<Resource<ResultType>> { | |
return result | |
} | |
open fun onFetchFailed() {} | |
abstract fun shouldFetch(data: ResultType?): Boolean | |
abstract fun loadFromLocal(): Observable<ResultType> | |
abstract fun createCall(): Observable<Response<ResponseData<RequestType>>> | |
abstract fun saveCallResult(item: RequestType) | |
} |
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
data class Resource<out T>(val data: T?, val message: String?) { | |
companion object { | |
fun <T> success(data: T?): Resource<T> { | |
return Resource(data, null) | |
} | |
fun <T> error(msg: String, data: T?): Resource<T> { | |
return Resource(data, msg) | |
} | |
fun <T> loading(data: T?): Resource<T> { | |
return Resource(data, null) | |
} | |
} | |
} |
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
data class ResponseData<T>( | |
var data: T?, | |
var code: Int, | |
var message: String? | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment