Thursday, September 27, 2018

rxjava + retrofit - How to wait and get the result of first observable in android?

Leave a Comment

I've recently started learning retrofit and rxjava. I'm looking for any ideas on how to wait ang get the result of first observable. Basically, I want to apply it on a simple login. The first api call is getting the server time. The second api call will wait the result of the first call (which is the server time) and utilize it.

                Retrofit retrofit = RetrofitClient.getRetrofitClient();                 LocalServerInterface apiInterface = retrofit.create(LocalServerInterface .class);                  Observable<ServerTime> timeObservable = retrofit                         .create(LocalServerInterface .class)                         .getTime()                         .subscribeOn(Schedulers.newThread())                         .observeOn(AndroidSchedulers.mainThread());                  Observable<ServerNetwork> serverNetworkObservable = retrofit                         .create(LocalServerInterface .class)                         .getNetworks(//valuefromapicall1, anothervalue)                         .subscribeOn(Schedulers.newThread())                         .observeOn(AndroidSchedulers.mainThread()); 

Now, I'm stuck right here. On second observable, particularly on getNetworks method, I wanted to use what I got from first observable. Any ideas?

EDIT:

I wanted to process first the result of call 1 before supplying it to the api call 2. Is it possible?

1 Answers

Answers 1

First, do not recreate LocalServerInterface each time, create one and reuse it. Creation of the instance of the interface is an expensive operation.

LocalServerInterface apiInterface = retrofit.create(LocalServerInterface.class) 

And to make the second observable start with the result of the first observable, you need to do flatMap.

Observable<ServerNetwork> serverNetworkObservable = apiInterface                         .getTime()                         .flatMap(time -> apiInterface.getNetworks(time, anothervalue))                         .subscribeOn(Schedulers.newThread())                         .observeOn(AndroidSchedulers.mainThread()); 

See the flatMap documentation for more info.

IMPORTANT NOTE. In this case, when only one response will be emitted by the first observable, there's no difference between using flatMap and concatMap. For the other cases, consider the difference between flatMap and concatMap.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment