Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 332
silent_coder14 Avatar asked Jan 01 '23 20:01

silent_coder14


1 Answers

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.

like image 138
Viktor K Avatar answered Jan 31 '23 08:01

Viktor K