I'm using RxJava and the concat()
and first()
operators:
public Observable<List<Entity>> getEntities() {
invalidateCacheIfNeeded();
return Observable
.concat(cachedEntities(), networkEntities())
.first();
}
The cachedEntities
returns an Observable built from a cached list while the networkEntities
method fetches the entities with Retrofit.
This works great unless two user subscribes quickly to the observables returned by getEntities()
. I guess the network request of the first subscribe is not finished when the second subscribe is made. In this case, two network requests are performed. Which I want to avoid.
I tried to create a single thread Scheduler so the the execution of the second call is only carried out when the first call is over but with no luck:
mSingleThreadScheduler = Schedulers.from(Executors.newSingleThreadExecutor());
and:
public Observable<List<Entity>> getEntities() {
invalidateCacheIfNeeded();
return Observable
.concat(cachedEntities(), networkEntities())
.subscribeOn(mSingleThreadScheduler)
.first();
}
I've tried to sprinkle the subscribeOn
call lower in the Observable chain but I get the same result.
Any hint?