0

I have 2 REST request methods; getA() and getB(). Both are asynchronous calls using call.enqueue().

I cannot call getB() until I have the results from getA(). In onCreateView(), I would call getA() and getB() consecutively. But, getB() would fail because it does not have the results from getA() yet. A way around this problem is, I could call getB() inside getA(), but I don't think that's clean coding.

Is there a way to wait until the request from getA() is completed before calling getB() in onCreateView()?

profound_swami
  • 103
  • 2
  • 7

2 Answers2

1

Call getB() from within the onResponse callback retrofit provides

call.enqueue(new Callback<Thing>() {
        @Override
        public void onResponse(Call<Thing> call, Response<Thing> response) {
            if (response.isSuccessful) {
                callB();
            }
        }

        @Override
        public void onFailure(Call<Thing> call, Throwable t) {
            // handle failure
        }
    });

The above will work, however, I'm a strong advocate for RxJava when handling Api calls with retrofit.

JakeB
  • 2,043
  • 3
  • 12
  • 19
1

You can also use ZIP operator from RxJava

Documentation

And example can be found here

theanilpaudel
  • 3,348
  • 8
  • 39
  • 67
  • I'm looking into it, but I am not understanding how it works. Could you explain how does using the `zip` operator from RXJava make the main thread to pause until the request has completed before resuming? – profound_swami Mar 17 '20 at 19:19