Skip to content

Instantly share code, notes, and snippets.

@Kashif-E
Created December 22, 2021 09:25
Show Gist options
  • Save Kashif-E/ff1dcec09f785318fe74eb6856cf3a2e to your computer and use it in GitHub Desktop.
Save Kashif-E/ff1dcec09f785318fe74eb6856cf3a2e to your computer and use it in GitHub Desktop.
this is how you make parallel api calls using Kotlin coroutines
override suspend fun doNetworkCallsInParallel() {
try {
CoroutineScope(Dispatchers.IO).launch {
val usNewsResponse = async {
apiServices.getHeadLines(country = "us")
}
val healthNewsResponse = async {
apiServices.getHeadLines(category = "health") }
val x = usNewsResponse.await()
val v = healthNewsResponse.await()
if (x.isSuccessful && v.isSuccessful){
Log.e("US Response", x.body().toString())
Log.e("Health", v.body().toString())
}
}
} catch (e: Exception) {
Log.e("Exception", e.localizedMessage)
}
}
Happy coding <3
@Kashif-E
Copy link
Author

@shahwaiz90 I don't think so are you using retrofit?

@shahzadansari
Copy link

isSuccessful is no longer accessible

@shahwaiz90 If you want to access Response object, check the return type of your ApiService function which is making the request. If the return type is of type Call, you need to use awaitResponse { } instead of await { } to get result as Response. Afterwards, you can access isSuccessful

Reference: https://youtu.be/S-10lLA0nbk

@seynth
Copy link

seynth commented Jun 2, 2024

@Kashif-E hey can i call 2 api like 2 baseUrl with retrofit 2 and use the coroutines to get the response?

@Kashif-E
Copy link
Author

Kashif-E commented Jun 3, 2024

@seynth For that there are two ways, you either create two separate retrofit instances and use them to call APIs in parallel, or create separate instances of interceptors to handle two different base URLs, and passing them to retrofit at run time and making async calls

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment