0

I want to make an api request, then I need to make two more requests after I receive the data. I found a great SO answer that uses rxjava2 to make two concurrent requests here:

How to make multiple request and wait until data is come from all the requests in retrofit 2.0 - android

I suppose I could just chain the logic for this after the first request, but my intuition tells me thats a bad idea because I'd be duplicating some code (I'd have separate logic for the first request in a function, then some similar logic for the second two requests in a function)

Is there a better way to accomplish this? I'd prefer Kotlin, but Java is ok.

Here is the code for concurrent requests from the SO answer.

  val retrofit = Retrofit.Builder()
            .baseUrl("https://api.example.com/")
            .build()

    val backendApi = retrofit.create(MyBackendAPI::class.java)

    val requests = ArrayList<Observable<*>>()

    requests.add(backendApi.getUser())
    requests.add(backendApi.listPhotos())
    requests.add(backendApi.listFriends())

    Observable
            .zip(requests) {
                // do something with those results and emit new event
                Any() // <-- Here we emit just new empty Object(), but you can emit anything
            }
            // Will be triggered if all requests will end successfully (4xx and 5xx also are successful requests too)
            .subscribe({
                //Do something on successful completion of all requests
            }) {
                //Do something on error completion of requests
            }

Thanks

Louis Sankey
  • 481
  • 8
  • 26
  • 2
    Since Retrofit 2.6.0 with Kotlin you can define your retrofit interface methods as suspend functions and just seamlessly run and chain them within a coroutine scope. – Pawel Jul 08 '21 at 19:24
  • That sounds promising, and I'll look into it. Would you happen to have a code sample for that? – Louis Sankey Jul 08 '21 at 19:27

0 Answers0