Viktor Vostrikov
Viktor Vostrikov

Reputation: 1542

Subscribe to an Observable once and use its value multiple times in RxJava

I am using flatMap as an indicator then should I fire another network request.

  Observable<ResponseBody> secoondRequest =  firstRequest.flatMap(responseBody -> {
            return RetrofitFactory.create().setIssuingCountry(countrySetRequest1);
        });

The problem is that I have more than one secondRequest Observable, so my firstRequest executes multiple times.. I only need for it to trigger once for all other observables..

  //This should not call firstRequest again, if it was already triggered once
Observable<ResponseBody> secoondRequest2 =  firstRequest.flatMap(responseBody -> {
            return RetrofitFactory.create().setIssuingCountry(countrySetRequest1);
        });

Upvotes: 1

Views: 1097

Answers (2)

Adib Faramarzi
Adib Faramarzi

Reputation: 4060

You need to save your firstObservable in a variable and use share() and replay() to make it execute once (first observable will be subscribed once) from multiple source, but its value is emitted to multiple second observables.

Observable<Something> firstObservable = firstRequest().share().replay()
Observable<ResponseBody> secoondRequest2 =  firstObservable.flatMap(responseBody -> {
        return RetrofitFactory.create().setIssuingCountry(countrySetRequest1);
    });

Upvotes: 0

Manu
Manu

Reputation: 422

It is not entirely clear what your usecase is. So I am assuming that you have multiple requests that depend on the response of the first request. That is

request1 <- request2, request3, request4.... One possible way to solve problem is as below

Observable<ResponseBody> firstRequest = firstRequest();

Observable<ResponseBody> finalRequest = firstRequest.flatMap(responseBody -> {
 return RetrofitFactory.create().setIssuingCountry(countrySetRequest1)
.merge(RetrofitFactory.create().setIssuingCountry(countrySetRequest1))
.merge(RetrofitFactory.create().setIssuingCountry(countrySetRequest1))
.merge(RetrofitFactory.create().setIssuingCountry(countrySetRequest1))
...
}

Upvotes: 0

Related Questions