1

I have ServerTime class:

public class ServerTime {

    private String time;

    public ServerTime(String time) {
        this.time = time;
    }    
    public String getTime() {
        return time;
    }
}

And ServerNetwork class:

public class ServerNetwork {

    private String id;
    private String name;

    public ServerNetwork(String id, String name) {
        this.id = id;
        this.name = name;
    }    
    public String getId() {
        return id;
    }
   public String getName(){
        return name;
   }
}

Now what I wanted to do is process this sequentially since I have to supply timestamp to the second api call. So far I have this but I'm unsure how to process the first observable result, like converting it to a timestamp and then using it for the second observable api request.

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

How do I go about starting these observables to actually call the api? I'm new to RxJava.

chornge
  • 2,021
  • 3
  • 28
  • 37
silent_coder14
  • 583
  • 2
  • 10
  • 38

1 Answers1

0

Try:

apiInterface.getTime()
            // specify thread for performing network call.
            .subscribeOn(Schedulers.newThread())

            // use emissions from 1st Observable in 2nd Observable.
            .flatMap(serverTime -> {
                String anotherValue = "";
                return apiInterface.getNetworks(serverTime.getTime(), anotherValue);
            })

            // switch to computation thread to transform emissions (optional)
            .observeOn(Schedulers.computation())

            // transform emissions from Observable<ServerNetwork> to Observable<String> (corresponding network ids).
            .map(ServerNetwork::getId)

            // switch to UI thread to consume the transformed emissions.
            .observeOn(AndroidSchedulers.mainThread());
            .subscribe(serverNetworkId -> {
                // update views, etc
                textView.setText(serverNetworkId);
            });

This is the inferred interface:

public interface ApiInterface {
    @(...)
    Observable<ServerTime> getTime();

    @(...)
    Observable<ServerNetwork> getNetworks(@Body String timeStamp, @Body String anotherValue);
}

Note: Since you did not include code for your ApiInterface.class file I have tried to infer what that file may contain. I have also included some comments to explain what is going on under the hood to add some clarity. I included an optional operator .map() and used multiple observeOn, they are completely optional.

chornge
  • 2,021
  • 3
  • 28
  • 37