How to make multiple network call efficiently using coroutine

38 views Asked by At

I am building an app using CatApi.

There are paginated list of items which gives image_ref_id and using that id I have to fetch images for all the items to show in feed.

What would be most efficiently approach for this ?

Update:

  1. In the feed response, I am getting the image_ref_id and using that I have make another api call to get the image url.

  2. Image api have another information as well which i want to consume.

2

There are 2 answers

1
m.reiter On

Image loading is something you don't need to do manually anymore, there are well established libraries for this, which display an image based on an url. They handle all that caching etc. for you

In case you're using compose, this might be e.g. coil

1
yunusemreyakisan On
interface CatApi {
@GET("/v1/breeds")
Call<List<CatItem>> getCats(@Query("page") int page, @Query("limit") int limit);

@GET("/v1/images/{image_ref_id}")
Call<CatImage> getImageDetails(@Path("image_ref_id") String imageRefId); }

you should use interface like this and UPDATED

private suspend fun fetchCatFeed(int page: Int, int limit: Int) {
try {
    // 1. Fetch initial CatItems data
    val catItems = catApi.getCats(page, limit)

    // 2. Create a list of coroutines for fetching image details
    val imageUrlsAndDetails = catItems.map { item ->
        async {
            // 3. Fetch image details for each CatItem
            val catImage = catApi.getImageDetails(item.image_ref_id)
            val imageUrl = catImage.imageUrl

            // 4. Combine image URL with other relevant details (if needed)
            Pair(imageUrl, // other details from catImage...) // Adjust as needed
        }
    }

    // 5. Wait for all image details to be fetched concurrently
    val results = imageUrlsAndDetails.map { deferred -> deferred.await() }

    // 6. Update feed UI with fetched results (image URLs and details)
    // Use results in a loop or adapter to update individual feed items
    for (result in results) {
        val imageUrl = result.first // Access image URL from the Pair
        // Update feed item with imageUrl and other details (if applicable)
    }
} catch (e: Exception) {
    // 7. Handle errors gracefully (network issues, API failures, etc.)
    // Display error message or implement retry mechanism (optional)
    Log.e("CatApi", "Error fetching feed data: ${e.message}")
}}