SmartCache
SmartCache copied to clipboard
Using this with RxJava2
Not sure if this can be used together with RxJava2CallAdapterFactory, since then I can't use SmartCall in my interface. I have to use Observable, which means the SmartCacheFactory will not work.
Here's the simple implementation (in Kotlin) I came up with for wrapping a SmartCall into an Observable. I could potentially create a Factory for it, just not sure how to yet. Depending on if I have time, I'll do that and open a PR! But for now this works for us:
class SmartCacheObservable<T>(private val call: SmartCall<T>): Observable<T>() {
override fun subscribeActual(observer: Observer<in T>) {
val call = call.clone()
call.enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>?, response: Response<T>) {
val body = response.body()
if (body != null) {
observer.onNext(body)
} else {
observer.onError(Throwable("Could not read response body!"))
}
// The current version of SmartCache will set the url to "http://localhost/" for
// cached responses, we can use that to wait until the real network request
// completes to call `observer.onComplete()`
if (response.raw().request().url().host() != "localhost") {
observer.onComplete()
}
}
override fun onFailure(call: Call<T>?, error: Throwable) {
observer.onError(error)
observer.onComplete()
}
})
}
}
Hi , andreyrd I am using retrofit 2 with RX java , i Need to show data from cache before network call , As i am using rx java so here i can not use SmartCacheFactory . do you have any solution for that
Hey, @bhoopendrayash, I believe you can just use a Java version of my SmartCall wrapper. I'll try to find time later today to convert and test it in Java, unless someone else does it first.
Hey @andreyrd , Thank you so much for your quick response , i will try to convert your SmartCacheObservable class to java
@bhoopendrayash have you found a solution?
hello i too is facing this issue how can it be used with rxjava
@gzodx @dula34 @andreyrd Hey, I've released a new version with Retrofit 2.9, and some niceties: a new demo app, a function for checking if current callback is loaded from disk, clearing cache and a way to filter for which requests should be cached.
Change the repo username to fikisipi
and use SmartCache:2.9.0
from JitPack. I don't have experience with RxJava but I'd love to see a PR or help with adding that as well.