0
votes

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.

1

1 Answers

1
votes

Seems this article would be of help!

It keeps the Observables for API calls in a Map, and returns the same for future API calls.

Leave some claps for the author if it works out for you