I have a method that returns Observable which does an API call, it is part of multiple observable in many place of the app (as they are using same data). Currently even as I'm caching result of that API call it happens that method which returns Observable to API is called multiple times at the same time. In such case app is doing multiple requests. How I can return same API call that is in progress (or observable) so there is only one ongoing API call at the same time?
Sample code below:
var cache: ApiResponse? = null
fun getApiCall() : Observable<ApiResponse> {
return if(cache != null) {
Observable.just(cache)
} else {
Observable.just(retrofitClient.doApiCall())
.map {
doSomeStuffWithOutput()
cache = it
}
}
}
I thought of CompositeDisposable or .cache() operator but the issue is that is it a part of the observable chain and subscribe it much higher in method calls, and this method is used in multiple Observables.